# 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

조회 수: 49(최근 30일)
Colm Murphy 23 Oct 2019
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);

로그인 to comment.

### 채택된 답변

Image Analyst 23 Oct 2019
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);

#### 댓글 수: 1

Colm Murphy 23 Oct 2019
That worked. Thank you.

로그인 to comment.

### 추가 답변(2개)

James Tursa 24 Oct 2019
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

#### 댓글 수: 0

로그인 to comment.

Navadeep Ganesh U 30 Nov 2019
use "hold on" for keeping plots.

#### 댓글 수: 0

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.

Translated by