MATLAB: Getting an error : In an assignment A(:) = B, the number of elements in A and B must be the same. with the multiple plotting code!

errorMATLABplotplotting

x= 0:0.01:pi;
n= length(x);
y= zeros(1,n);
for plots = 1:3
if plots ==1
for k= 1:n
y(k)= sign(x(k));
end
elseif plots==2
x = pi:0.01:2*pi;
for k= 1:n
y(k)= (-0.81057*(x.^2)) + ((7.63944*x) - 19);
end
elseif plots==3
x = 2*pi:0.01:3*pi;
for k= 1:n
y(k)= (-1.6211*(x.^2)) + ((25.465*x) - 96);
end
end
plot(x,y,'r*-')
hold on
end
hold off
Having two errors :
In an assignment A(:) = B, the number of elements in A and B must be the same.
Error in (line 12)
y(k)= (-0.81057*(x.^2)) + ((7.63944*x) – 19);

Best Answer

hello
error is due to lack of indexing x on the right hand side of the equations
x= 0:0.01:pi;
n= length(x);
y= zeros(1,n);
for plots = 1:3
if plots ==1
for k= 1:n
y(k)= sign(x(k));
end
elseif plots==2
x = pi:0.01:2*pi;
for k= 1:n
y(k)= (-0.81057*(x(k).^2)) + ((7.63944*x(k)) - 19);
end
elseif plots==3
x = 2*pi:0.01:3*pi;
for k= 1:n
y(k)= (-1.6211*(x(k).^2)) + ((25.465*x(k)) - 96);
end
end
plot(x,y,'r*-')
hold on
end
hold off
%% but that code is not optimal : there is NO need for for loops (makes only code run slower)
% consider this :
x= 0:0.01:pi;
n= length(x);
y= zeros(1,n);
for plots = 1:3
if plots ==1
y= sign(x);
elseif plots==2
x = pi:0.01:2*pi;
y= (-0.81057*(x.^2)) + ((7.63944*x) - 19);
elseif plots==3
x = 2*pi:0.01:3*pi;
y= (-1.6211*(x.^2)) + ((25.465*x) - 96);
end
plot(x,y,'r*-')
hold on
end
hold off
Related Question