Plotting a graph
显示 更早的评论
Sorry, this is a very simple question I'm sure but I just can't work it out. I'm trying to plot the error of my function that ascertains e^x for a value of x. However, when I try and plot the vectors containing the relevant information I get a load of errors.
My M-file:
function T = findexp(x,n)
%findexp, function to evaluate e^x
e=zeros(1,n);
T(1)=1;
e(1)=abs(T(1)-exp(x))/x;
for i = 2:n+1
T(i) = T(i-1)+x^(i-1)/(factorial(i-1));
e(i) = abs((T(i)-exp(x))/(x));
if i == n+1
fprintf(1,'T(%d) = %1.15e\n',x,T(i));
end
end
p=1:1:n+1;
y=e(p);
plot(p,y)
However, what I get is the output:
EDU>> findexp(1,25) T(1) = 2.718281828459046e+000 ??? Input argument "n" is undefined.
Error in ==> error at 4 e(i) = abs((findexp(x,n)-exp(x))/x);
Error in ==> clo at 20 error(nargchk(1, 3, nargin));
Error in ==> cla at 29 clo(ax, extra{:});
Error in ==> newplot>ObserveAxesNextPlot at 134 cla(ax, 'reset',hsave);
Error in ==> newplot at 83 ax = ObserveAxesNextPlot(ax, hsave);
Error in ==> findexp at 17 plot(e,p)
What am I doing wrong? Thanks for your help in advance
2 个评论
the cyclist
2012-1-19
It would be really helpful if you spent some time formatting your question better, using the Code button better.
Harry
2012-1-19
采纳的回答
更多回答(1 个)
the cyclist
2012-1-19
I put the following lines of code into a file called "findexp.m"
function T = findexp(x,n)
%findexp, function to evaluate e^x
e=zeros(1,n);
T(1)=1;
e(1)=abs(T(1)-exp(x))/x;
for i = 2:n+1
T(i) = T(i-1)+x^(i-1)/(factorial(i-1));
e(i) = abs((T(i)-exp(x))/(x));
if i == n+1
fprintf(1,'T(%d) = %1.15e\n',x,T(i));
end
end
p=1:1:n+1;
y=e(p);
plot(p,y)
and then called them like this:
>> findexp(1,25)
That worked fine for me. It seems to me that the problem is not in your function findexp(), but rather in how you call it. It looks from your error message that you have not defined the second input argument, n, when you call findexp().
类别
在 帮助中心 和 File Exchange 中查找有关 Creating, Deleting, and Querying Graphics Objects 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!