Reputation: 946
I am beginner in matlab programming, so i wrote this little programm to see it in action, and now I have a little problem because I am not sure why it is not working.
x = zeros(50);
squared = zeros(50);
cubed = zeros(50);
for num = 1:50
x(num) = num;
squared(num) = num^2;
cubed(num) = num^3;
end
% calculate the mean
mean_cubed = mean(cubed);
% clear screen and hold the plot
clf;
hold on
plot(x, squared);
plot(x, cubed);
plot([0, 50], [mean_cubed, mean_cubed]);
hold off
The main program is when i start the program i get a error:
Error using plot
Vectors must be the same lengths.
Error in basic_mathlab_plotting_2 (line 20)
plot([0, limit], [mean_cubed, mean_cubed]);
I think the size of vector are the same, so i dont know what is wrong.
Thanks!!!
Upvotes: 0
Views: 67
Reputation: 112659
In the first lines, you probably meant
x = zeros(1,50);
squared = zeros(1,50);
cubed = zeros(1,50);
Note that zeros(50)
is equivalent to zeros(50,50)
and so it returns a 50x50 matrix.
In addition, those lines and the for
loop could be replaced by
x = 1:50;
squared = x.^2;
cubed = x.^3;
This applies the important concept of vectorization, by using the element-wise power operation.
Upvotes: 2