why the plot command is not plotting negative values?

10 vues (au cours des 30 derniers jours)
Manjunath GM
Manjunath GM le 2 Jan 2019
Commenté : Samuel le 5 Mar 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.

Réponse acceptée

madhan ravi
madhan ravi le 2 Jan 2019
Modifié(e) : madhan ravi le 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

Plus de réponses (0)

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by