
why the plot command is not plotting negative values?
32 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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 Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!