why the plot command is not plotting negative values?

조회 수: 10 (최근 30일)
Manjunath GM
Manjunath GM 2019년 1월 2일
댓글: Samuel 2024년 3월 5일
clc
for i=-5:1:20
if i>=9
y(i)=10*sqrt(2*i)+5;
elseif (0<i)&&(i<=9)
y(i)=5*i+5;
else y(i)=5;
end
end
plot(y,'-b*');
axis([-5 25 0 80]);
in the above script i like to plot y for all i values but it is showing error that the index must be positive for -5 to 0.

채택된 답변

madhan ravi
madhan ravi 2019년 1월 2일
편집: madhan ravi 2019년 1월 2일
Use logical indexing :
n=-5:20;
y=5*ones(size(n));
y((0<n)&(n<=9))=5*n((0<n)&(n<=9))+5;
y(n>=9)=10*sqrt(2*(n(n>=9)))+5;
plot(n,y,'-b*');
hold on
axis([-5 25 0 80]);
If you still want to use loop then:
n=-5:20;
y=zeros(size(n)); % preallocate
for i=1:numel(n)
if n(i)>=9
y(i)=10*sqrt(2*n(i))+5;
elseif (0<n(i))&&(n(i)<=9)
y(i)=5*n(i)+5;
else
y(i)=5;
end
end
plot(n,y,'-b*');
axis([-5 25 0 80]);
Note: You had error because you tried to index y with negative value but Matlab indexing starts from 1 and it's always positive.
That is
x = 1:10; % an example
x(-1) % gives error
x(1) % doesn't error out

추가 답변 (0개)

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by