How can I plot sin(x),sin​(2x),...,s​in(nx) for an input n all on the same graph? Matrix dimensions must agree error

12 ビュー (過去 30 日間)
I'm trying to plot sin(x) and sin(2x) and 3x and so on up to sin(nx) all on the same graph. My code right now is as follows.
x=[-2*pi:pi/64:2*pi];
i = input('Enter a positive whole number: \n');
z=[1:i];
y=sin(x.*z);
for z = [1:i]
plot(x,y);
end
It's giving me an error saying:
Matrix dimensions must agree.
Error in lab5_exercise2 (line 9)
y=sin(x.*z);

採用された回答

Image Analyst
Image Analyst 2019 年 10 月 23 日
Put the y= statement inside the loop:
x = -2*pi : pi/64 : 2*pi;
n = input('Enter a positive whole number: ');
for z = 1 : n
y = sin(x.*z);
plot(x,y, '.-');
hold on;
end
grid on;
xlabel('x', 'FontSize', 15);
ylabel('Y', 'FontSize', 15);

その他の回答 (2 件)

James Tursa
James Tursa 2019 年 10 月 24 日
Modifying your original code without a loop:
x=[-2*pi:pi/64:2*pi];
i = input('Enter a positive whole number: \n');
z=[1:i]'; % make this a column vector
y=sin(x.*z); % use implicit expansion
plot(x,y); % no need for a loop
grid on

Navadeep Ganesh U
Navadeep Ganesh U 2019 年 11 月 30 日
use "hold on" for keeping plots.

カテゴリ

Help Center および File Exchange2-D and 3-D Plots についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by