why the plot command is not plotting negative values?

64 Ansichten (letzte 30 Tage)
Manjunath GM
Manjunath GM am 2 Jan. 2019
Kommentiert: Samuel am 5 Mär. 2024
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.

Akzeptierte Antwort

madhan ravi
madhan ravi am 2 Jan. 2019
Bearbeitet: madhan ravi am 2 Jan. 2019
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

Weitere Antworten (0)

Kategorien

Mehr zu Function Creation finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by