Sometimes we want to define a function to use several times

Sometimes we want to define a function to use several times, or in different ways, in a code. MATLAB allows us to define ‘anonymous functions’; the name of the function is called the handle. There is a specific syntax that must be used in the definition: the independent variables follow the at sign in parentheses: f = @(x) x.^2+1; g = @(x,y) x ./ (y.^3+x+1); Here, x and y are dummy variables that have no specific values. Here are some examples of how to use these functions: f = @(x) x.^2+1; f(3) x=[1,2,3] f(x) x=0:.01:5; y = f(x); figure(1) plot(x,y) figure(2) plot(x,f(x)) g = @(x,y) x ./ (y.^3+x+1); g(1,2) g(5,6) g([1 2],[5 6]) Your assignment is to define f(x) = e x sin x x 2 + 1 as an anonymous function and plot it on [3, 7] using poor resolution and good resolution (same h values as before) in one plot, with dots for the poor resolution, as in the previous problem.

Solution

to pass parameters using anonymous functions:

write a file containing the following code

function y = parameterfun(x,a,b,c)

y= (a-b*x(1)^2 + x(1)^(4/3)* x(1)^2 + x(1) * x(2) +..... (-c + c * x(2)^2)* x(2) ^ 2

1.Assign values to the parameters

a=4;b=2.1;c=4

x0=[0:5,0:5]

[x,fval] = fminunc(f,X0)

taking different values of x gives different f(x) values which gives a plot

Sometimes we want to define a function to use several times, or in different ways, in a code. MATLAB allows us to define ‘anonymous functions’; the name of the

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site