Hi I am new to matlab so not familiar with its grammar.
I want to write a function to solve some functions using specific algo.
What I want to do is to write a function using another function which I want to slove as input.
For example, if I want to get the root of x^2 - 1 = 0 ,I need to plug in this function as in input.
my code is like
function [y] = brent(f, x0, x1, max_iter, tolerance)
fx0 = f(x0)
fx1 = f(x1)
......
end
f is the function I want to solve. My question is how should I write the code so the function 'brent' can use the function 'f' to calculate the values at specific points.
ex. In the second line, I need to get the value of f(x0) (x0 is a point).
Matlab talks about function handles. Those can be input parameter as anything:
Write your main function:
function a = func(f,x)
a = f(x) + 7;
Define your function to be input, and call 'normally'
>> myfun = #(x) x^2-1;
>> func(myfun,3)
ans =
15
>> func(#sin,0)
ans =
7
see:
https://se.mathworks.com/help/matlab/matlab_prog/creating-a-function-handle.html
Related
So i'm a little confounded by how to structure my problem.
So the assignment states as following:
Type a m-file numerical_derivative.m that performs numerical derivation. Use
it to calculate f'(-3) when f(x) = 3x^2 /(ln(1-x))
In the m-file you to use h = 10^-6 and have the following mainfunction:
function y = numericalderivative (f, x)
% Calculates the numerical value in the case of f in punk x.
% --- Input ---
% f: function handle f(x)
% x: the point where the derivative is calculated
% --- output ---
% y: the numerical derivative of f on the point x
If I want to save it as a file and run the program in matlab, does't it make it redundant to use handles then?
I won't give you the answer to your homework, but perhaps a simpler example would help.
Consider the following problem
Write a function named fdiff which takes the following two arguments:
A function f represented by a function handle which takes one argument,
and a point x which can be assumed to be in the domain of the f.
Write fdiff so that it returns the value f(x) - f(x-1)
Solution (would be in the file named fdiff.m)
function result = fdiff(f, x)
result = f(x) - f(x-1);
end
Example Use Cases
>> my_function1 = #(x) 3*x^2 /(log(1-x));
>> fdiff(my_function1, -3)
ans =
-10.3477
>> my_function2 = #(x) x^2;
>> fdiff(my_function2, 5)
ans =
9
What you've created with fdiff is a function which takes another function as an input. As you can see it doesn't just work for 3*x^2 /(log(1-x)) but any function you want to define.
The purpose of your assignment is to create something very similar, except instead of computing f(x) - f(x-1), you are asked write a function which approximates f'(x). Your use-case will be nearly identical to the first example except instead of fdiff your function will be named numericalderivative.
Note
In case it's not clear, the second example defines the my_function2 as x^2. The value returned by fdiff(my_function2, 5) is therefore 5^2 - 4^2 = 9.
When you make this as a function file and run this in MATLAB without any input arguments i.e., 'f' and 'x', it will give you the error: 'not enough input arguments'. In order to run the file you have to type something like numericalderivative (3x^2 /(ln(1-x)), 5), which gives the value of the numerical derivative at x = 5.
Functions and, in MATLAB function files are a simple implementation of the DRY programming method. You're being asked to create a function that takes a handle and an x file, then return the derivative of that function handle and that x value. The point of the function file is to be able to re-use your function with either multiple function handles or multiple x values. This is useful as it simply involves passing a function handle and a numeric value to a function.
In your case your script file or command window code would look something like:
func = #(x) (3*x^2)/log(1-x);
x = -3;
num_deriv = numericalderivative(func,x);
You should write the code to make the function numericalderivative work.
When I type help gmres in MATLAB I get the following example:
n = 21; A = gallery('wilk',n); b = sum(A,2);
tol = 1e-12; maxit = 15;
x1 = gmres(#(x)afun(x,n),b,10,tol,maxit,#(x)mfun(x,n));
where the two functions are:
function y = afun(x,n)
y = [0; x(1:n-1)] + [((n-1)/2:-1:0)'; (1:(n-1)/2)'].*x+[x(2:n); 0];
end
and
function y = mfun(r,n)
y = r ./ [((n-1)/2:-1:1)'; 1; (1:(n-1)/2)'];
end
I tested it and it works great. My question is in both those functions what is the value for x since we never give it one?
Also shouldn't the call to gmres be written like this: (y in the #handle)
x1 = gmres(#(y)afun(x,n),b,10,tol,maxit,#(y)mfun(x,n));
Function handles are one way to parametrize functions in MATLAB. From the documentation page, we find the following example:
b = 2;
c = 3.5;
cubicpoly = #(x) x^3 + b*x + c;
x = fzero(cubicpoly,0)
which results in:
x =
-1.0945
So what's happening here? fzero is a so-called function function, that takes function handles as inputs, and performs operations on them -- in this case, finds the root of the given function. Practically, this means that fzero decides which values for the input argument x to cubicpoly to try in order to find the root. This means the user just provides a function - no need to give the inputs - and fzero will query the function with different values for x to eventually find the root.
The function you ask about, gmres, operates in a similar manner. What this means is that you merely need to provide a function that takes an appropriate number of input arguments, and gmres will take care of calling it with appropriate inputs to produce its output.
Finally, let's consider your suggestion of calling gmres as follows:
x1 = gmres(#(y)afun(x,n),b,10,tol,maxit,#(y)mfun(x,n));
This might work, or then again it might not -- it depends whether you have a variable called x in the workspace of the function eventually calling either afun or mfun. Notice that now the function handles take one input, y, but its value is nowhere used in the expression of the function defined. This means it will not have any effect on the output.
Consider the following example to illustrate what happens:
f = #(y)2*x+1; % define a function handle
f(1) % error! Undefined function or variable 'x'!
% the following this works, and g will now use x from the workspace
x = 42;
g = #(y)2*x+1; % define a function handle that knows about x
g(1)
g(2)
g(3) % ...but the result will be independent of y as it's not used.
I'm implementing a ML receiver for a communication channel.
For this I need to find the minimum value of the function below with respect to x in the range x = 0 to 15 (16QAM)
f = abs( rx(n) - (h'*h)*x )^2 ;
I have to iterate this in a loop (n=1:100). I found that I can do this by matlab function x = fminbnd(fun,x1,x2) where I can put the function in a separate .m-file as:
function f = myfun(x)
f = abs( rx(n) - (h'*h)*x )^2
and find the minimum for x from
x = fminbnd(#myfun,x1,x2);
My question is since constants to the function rx(n) is changing thorough the loop, how to sent it to the function myfun(x) within the loop.
You can do it by using an anonymous function to call your function in a separate file:
function mainfcnmin
h = [1;1];
rx = 1:3;
for n = 1:length(rx)
x = fminbnd(#(x)myfun(x,rx(n),h),0,15)
end
end
function f = myfun(x,rx,h)
f = abs(rx-(h'*h)*x)^2 ;
end
Or alternatively in one file by defining the function directly in the anonymous function like this:
h = [1;1];
rx = 1:3;
for n = 1:length(rx)
x = fminbnd(#(x)(abs(rx(n)-(h'*h)*x)^2),0,15)
end
You will need to make a function with rx(n) as a second parameter and then turn it into a single parameter anonymous function inside the loop.
Here is an example from the MATLAB documentation (for 'fminsearch' function):
If fun is parameterized, you can use anonymous functions to capture
the problem-dependent parameters. For example, suppose you want to
minimize the objective function myfun defined by the following
function file:
function f = myfun(x,a)
f = x(1)^2 + a*x(2)^2;`
Note that myfun has an extra parameter a, so you cannot pass it directly to > fminsearch. To optimize for a specific value of a, such as a = 1.5.
Assign the value to a
a = 1.5; % define parameter first
Call
fminsearch with a one-argument anonymous function that captures that
value of a and calls myfun with two arguments:
x = fminsearch(#(x) myfun(x,a),[0,1])
Hope that helped (sorry for bad text formatting).
I have the following anonymous function:
f = #(x)x^2+2*x+1
I'm using this so that I use it in the following way:
f(0) = 1
But what if I want to find the derivative of such a function while still keeping it's anonymous function capability? I've tried doing the following but it doesn't work:
f1 = #(x)diff(f(x))
but this just returns
[]
Any thoughts on how to accomplish this?
Of course I could manually do this in 3 seconds but that's not the point...
If you have symbolic math toolbox, you can use symbolic functions to achieve the desired as follows:
syms x
myFun=x^2+2*x+1;
f=symfun(myFun,x);
f1=symfun(diff(f),x);
%Check the values
f(2)
f1(2)
You should get 9 and 6 as answers.
When you do diff of a vector of n elements it just outputs another vector of n-1 elements with the consecutive differences.. so when you put a 1 element vector you get an empty one.
A way to go would be to decide an epsilon and use the Newton's difference quotient:
epsilon = 1e-10;
f = #(x) x^2+2*x+1;
f1 = #(x) (f(x+epsilon) - f(x)) / epsilon;
or just do the math and write down the formula:
f1 = #(x) 2*x+2;
http://en.wikipedia.org/wiki/Numerical_differentiation
#jollypianoman this works to me. Actually you need to say that the symfun has to be evaluate using eval command, then you get all the features of an anonymous function. the best is to read the example below...
clear
N0=1;N1=5;
N=#(t) N0+N1*sin(t);
syms t
Ndot=symfun(diff(N(t)),t);
Ndot_t=#(t) eval(Ndot);
Ndot_t(0)
ans = 5
Ndot_t(1)
ans = 2.7015
[tstop] = fsolve(Ndot_t,pi/3)
tstop =
1.5708
cheers,
AP
i want to create a function (symfun), and i want to divide it to cases, i.e if t> then then answer will be a and if t<0 the answer will be b.
the thing is, that matlab wont allow me to put an if statements after a sym function.
>> l = symfun(0, [m]);
>> l(m) = if m>0 3
also i tried to create a function:
function [x1] = xt_otot_q3(t)
and tried to connect between the two functions:
>> l(m) = xt_otot_q3(m)
Conversion to logical from sym is not possible.
is there any way to break a symfun into cases?
Not sure that I understand what you want.
This code 'combines' the functions symfun and xt+otot_q3 defined below:
function test;
m=randn(4); % N(0,1) random numbers
l=xtotot_q3(symfun(0,m)) % combine xt_otot_q3 and symfun
l=symfun(0,xtotot_q3(m)) % combine symfun and xt_otot_q3
return
function lval=symfun(thr,rval);
lval=ones(size(rval)); % output, size of input, = 1
lval(rval<thr)=-1; % output = -1 if input < thr
return
function lval=xtotot_q3(rval);
lval=3*rval+1; % some function, in this case 3 * input + 1
return
You can save the whole bit as test.m and then call test from the matlab prompt. Maybe if you start with this then you can modify it to fit your needs.