Matlab function that returns gradient - matlab

I'm trying to create a function, that has two output arguments:
1. The calculated f(x) value
2. The gradient
But it's calling itself recursively all the time.
What am I doing wrong?
function [y, gra] = f1(x)
y = x^2
syms z
gra = gradient(f1(z))
Thanks.
edit:
Now I have this:
function [y, gra] = f1(x)
y = x^2
if nargout == 2
syms x
gra = gradient(f1(x))
end
edit 2:
I'm trying to use the function in the following:
[y, grad] = f1(5);
y_derived = grad(10);

I think this is what you want to do:
function [y, gra] = f1(x)
f=#(x) x^2;
y=f(x); %// calculate y
syms z %// initialise symbolic variable
gra=gradient(f(z),z); %// symbolic differentiation
This will return g as a symbolic function. To calculate a value, you can use subs(gra,z,123), or, if you are going to evaluate it many times, do gradFunc=matlabFunction(gra) then gradFunc(v) where v is a vector or matrix of points you want to evaluate.

That's because the argument into gradient is your function name f1(z). As such, it keeps calling f1 when your original function is also called f1, and so the function keeps calling itself until you hit a recursion limit.
I think you meant to put gradient(y) instead. Try replacing your gradient call so that it is doing:
gra = gradient(y);

Related

The Secant Method: a variant of the Newton-Raphson method

I have to code the Secant Method: a variant of the Newton-Raphson method.
I have done the following:
function [SecantMethod] = SecantMethod(x0, x1);
%this is a variation on the Newton-Raphson MEthod, uses two inital guesses
%so that we do not have to explicitly work of the derivative of f(x).
x0 = 2;
x1 = 1;
%the two guesses
f0 = f(x0);
f1 = f(x1);
%two coressponding values of the function evaluated at x0 and x1
x = x1 - (f1*((x1 - x0)/(f1 - f0)));
%actual Secant Method (finds x axis intercept between two guesses
end
When I run the code in Matlab, an error appears "Undefined function or variable 'f'."
I dont have any particular function that I want to solve I just have to code it so I am not sure how to do so.
You can have a function take a function as an argument as follows:
function [SecantMethod] = SecantMethod(f,x0, x1);
disp(f(x0));
end
Then in your code:
%make anonymous function:
f=#(x)(x.^2);
%or:
f=#sin;
%and simply:
SecantMethod(f,1,2)
% or just:
SecantMethod(#myfucntion,1,2)

Integral piecewise function matlab

I am trying to integrate a function F which is defined as:
function F
x = -3:0.1:3;
F = zeros(1, length(x));
for i = 1:length(x)
if (1.4<= x(i)) && (x(i) <= 1.6)
F(i) = x(i).^2;
else
F(i) = 2;
end
end
end
but the integral function gives me an error saying that there are too many arguments. I think the problem that the function is defined as a points?
The problem with your function, is that integral has no way to pass the arguments you supply to your function F. The function doesn't know that it can just pull certain elements from the vector you created. If you rewrite your function such that for an input (or x value), the output of F is returned, then integral will work as you need given two values to integrate between.

Plot ramp function

I am trying to plot a ramp function in MATLAB.
I have the following function for my ramp:
function [ y ] = ramp(x)
y=zeros(size(x));
y(x>=0)=linspace(0,x(end),length(x(x>=0)))
end
But, I want it to have a similiar effect as my step function
syms x
ezplot(5*heaviside(x-1), [-10, 10])
When I use this code:
syms x
ezplot(5*ramp(x-1), [-10, 10])
When I do (x-1) it seems to throw an error that it is impossible, may I ask for some modificaitons?:
Cannot prove '0 <= x - 1' literally. To test the statement mathematically,
use isAlways.
Your step function plot works with a function of symbolic variable x. But ramp, the way you have written it, is a function that expects numerical input (a vector of x-values). This is why your attempt to pass a symbolic x to it fails. Here is a correct way to plot this function:
x = linspace(-10,10,100);
plot(x, 5*ramp(x-1))
Alternatively, you can rewrite ramp as a function of a symbolic variable:
function y = symbramp(x)
y = (x+abs(x))/2;
end
and plot it as you did with Heaviside:
syms x
ezplot(5*symbramp(x-1), [-10,10])

Matlab plot ksdensity without first storing its arguments

In MATLAB, if I want to plot density of a variable V I have to do
[x, y] = ksdensity(V);
plot (y, x);
If I do plot(ksdensity(V)), it only plots x and not x Vs y.
Is there an easier alternative to give ksdensity() as an argument to plot() and do the same job as plot(y, x)?
You can refactor it into a function that takes in V and plots y vs x:
function h = plot_ksdensity(V, varargin)
[x, y] = ksdensity(V);
h = plot (y, x, varargin{:});
end
using varargin means you will still have access to plot options like colours. hold on will also still work because this just calls the regular plot function.
Unfortunately no. If you don't specify explicitly the outputs, a function will return always the leftmost one from output parameter list. To convince yourself about that, create the function ftest() somewhere in your MATLAB path:
function [x, y] = ftest( )
x = 1;
y = 2;
end
then call it in the Command Window without specifying the outputs
>> ftest()
ans =
1

How to calculate the integral of the exp of the sum of function handles in a cell

I don't know how to calculate the integral of the sum of function handles in a cell. Please see the below examples:
f{1} = #(x) x;
f{2} = #(x) x^2;
g = #(x) sum(cellfun(#(y) y(x), f));
integral(#(x) exp(g), -3,3);
Error: Input function must return 'double' or 'single' values. Found 'function_handle'.
PS: please don't change the formula, because this is just an example. My real problem is far more complicated than this. It has log and exp of this sum (integral(log(sum), -inf, inf)). So I can't break them up to do the integral individually and sum the integrals.I need to use sum(cellfun). Thank you.
Version: Matlab R2012a
Can anyone help me? Really appreciate.
You cannot add function handles, so anything that tries f{1}+f{2}+... would give an error.
But you can compute the integral of the sums like this, evaluating the function values one at a time and adding up the results:
function cellsum
f{1} = #(x) x;
f{2} = #(x) x.^2;
integral(#(x)addfcn(f,x), -3, 3)
end
function s = addfcn(f,x)
s = zeros(size(x));
for k = 1:length(f)
s = s + f{k}(x);
end
end
Note that x will usually be a vector when the integral command calls your functions with it. So your function definitions should be vectorized, .i.e., x.^2 instead of x^2, etc.