MATLAB: Why the plot command is not plotting negative values

plot

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.

Best Answer

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