How do I create a function, save it, then run feral on it?

1 view (last 30 days)
I'm new to matlab. I'm trying to do this practice problem attached but keep stumbling.
I have no idea how to do this.
So far I have this, but I keep getting an error stating "Not enough input arguments. Error in f (line 2) y = 2.*x.*cos(2.*x) - (x - 2).^2;"
>> h=(3-2)/130;
>> xvars1=2:h:3;
>> xvars2=0:h:2;
>> xvars3=3:h:4;
>> yvals1 = feval('myfilename',xvars1);
>> yvals2 = feval('myfilename',xvars2);
>> yvals3 = feval('myfilename',xvars3);
>> figure
>> plot(xvals1,yvals1)
>> title(“f(x)=2x*cos(2x)-(x-2)^2 between [2,3]”)
>> xlabel("x")
>> ylabel(“y”)
Not sure where I'm going wrong with this.

Accepted Answer

Askic V
Askic V on 18 Jan 2023
I understand this is homework, but you need to know that feval is not really necessary. Evan matlab suggest that.
You can use the following code snippet:
b = 3;
a = 2;
N = 130;
h = (b-a)/N;
xvals = a:h:b;
yvals = feval('my_function',xvals);
plot(xvals, yvals);
xlabel('x'); ylabel('y');
title('f(x)=2x*cos(2x)-(x-2)^2 between [2,3]');
function y = my_function(x)
y = 2*x.*cos(2*x)-(x-2).^2;
end
Normally, the function should be saved in a separate .m file with the same name as function, i.e. 'my_function.m'

More Answers (1)

Jayant Gangwar
Jayant Gangwar on 18 Jan 2023
Hi,
The equation you have shared is doing scalar multiplication which is done using ".*" in matlab, if you have used vector multiplication (done using "*") in the function you have defined it might be a reason for the error, I made the function according to the equation shared, given below and it is giving the required output
function y = myfilename(x)
y = 2.*x.*cos(2.*x)- (x-2).^2;
end
save the function as 'myfilename.m'.
The code to plot the data -
h=(3-2)/130;
xvars1=2:h:3;
xvars2=0:h:2;
xvars3=3:h:4;
yvals1 = feval('myfilename',xvars1);
yvals2 = feval('myfilename',xvars2);
yvals3 = feval('myfilename',xvars3);
figure
plot(xvars1,yvals1)
title("f(x)=2x*cos(2x)-(x-2)^2 between [2,3]")
xlabel("x")
ylabel("y")
This outputs the graph correctly.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!