我是matlab编程的初学者,所以我写了这个小程序来看它的实际应用,现在我有一点问题,因为我不确定它为什么不起作用。
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
主程序是当我启动程序时出现错误:
Error using plot
Vectors must be the same lengths.
Error in basic_mathlab_plotting_2 (line 20)
plot([0, limit], [mean_cubed, mean_cubed]);
我认为矢量的大小是一样的,所以我不知道出了什么问题。
感谢!!!
答案 0 :(得分:2)
在第一行中,您可能意味着
x = zeros(1,50);
squared = zeros(1,50);
cubed = zeros(1,50);
请注意,zeros(50)
相当于zeros(50,50)
,因此它返回50x50矩阵。
此外,这些行和for
循环可以替换为
x = 1:50;
squared = x.^2;
cubed = x.^3;
这适用于vectorization的重要概念,使用element-wise power操作。