why plot result is different from fplot's

조회 수: 171 (최근 30일)
pooneh shabdini
pooneh shabdini 2020년 3월 4일
댓글: Jesus Sanchez 2020년 3월 5일
function [ Y ] = cosin( n,x)
s=size(x,2);
Y=zeros(1,s);
for i=1:n
Y=Y+((((-1)^(i-1))*(x.^((2*i)-2)))/factorial((2*i)-2));
end
end
I used this function once in plot and then in fplot:
x=-pi:pi/10:pi;
Y=cosin(600,x);
plot(x,Y)
result of plot was this shape:
syms x
fplot(cosin(600,x))
the result of fplot was this:
why plot just show this small part of cos(x) and not more?

채택된 답변

Jesus Sanchez
Jesus Sanchez 2020년 3월 5일
Problem solved. The problem here is the value of n. Since you wrote that n = 600, the resulting number is too big for the computer to process, which assigns an Inf value to it. This is turns makes the result be a NaN as an output.
To sum up, the operation:
x.^(2*i)
should never be allowed to have an inf value. If you try to do:
5^(2*600); % My matlab gives me an infinite value here, its too big!
So the only thing that you need is to pay attention to the value of n. I set it to 100 and it is working properly for me now:
x = [-5:0.1:5];
y = cos(x); % Matlab
n = 100;
Y = cosin(n,x); % Own
figure
hold on
plot(x,y,'.-');
plot(x,Y);
legend('cos(x)','cosin(x)');
hold off
function [ Y ] = cosin( n,x)
s=size(x,2);
Y=zeros(1,s);
for i=0:n-1
%Y=Y+((((-1)^(i-1))*(x.^((2*i)-2)))/factorial((2*i)-2));
Y=Y+(((-1).^(i)).*(x.^(2.*i)))./factorial(2.*i);
end
end
  댓글 수: 2
pooneh shabdini
pooneh shabdini 2020년 3월 5일
Thank you:) Do you know why plot can't compute this big n=600 but fplot can?
Jesus Sanchez
Jesus Sanchez 2020년 3월 5일
If I understood the reference page, its because MATLAB uses n=23 as starting point and then performs an adaptive study of the solution, to find an optimal value Reference so I guess they force it to be less than that limit.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jesus Sanchez
Jesus Sanchez 2020년 3월 4일
For plot, you wrote that x is defined between -pi and pi.
For fplot, you can see the reason in its reference page
fplot(f) plots the curve defined by the function y = f(x) over the default interval [-5 5] for x.
  댓글 수: 6
Jesus Sanchez
Jesus Sanchez 2020년 3월 5일
I saw the result in matlab and it is indeed strange. The Taylor expansions resulting of Y gives "NaN" as a result for values of x that are not cointained within [-pi, pi].
The only mistake that I can see is that you have not written i-1 everywhere, so you are not implementeing correctly the function. I will give it more thought later!
pooneh shabdini
pooneh shabdini 2020년 3월 5일
I'll be thankful ?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Line Plots에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by