2010-08-29 25 views
4

我對Matlab非常陌生,我試圖做一個簡單的迭代腳本。 基本上所有我想要做的是劇情:試圖用MATLAB創建迭代(初學者)

1*sin(x) 
2*sin(x) 
3*sin(x) 
... 
4*sin(x) 

這是我寫的程序:

function test1 
x=1:0.1:10; 
for k=1:1:5; 
    y=k*sin(x); 
    plot(x,y); 
end % /for-loop 
end % /test1 

但是,它只繪製Y = 5 * SIN(X)或任何最後的號碼是...

任何想法?

謝謝! Amit

回答

7

您需要使用命令hold on來確保每次繪製新內容時繪圖都不會被擦除。

function test1 
figure %# create a figure 
hold on %# make sure the plot isn't overwritten 
x=1:0.1:10; 
%# if you want to use multiple colors 
nPlots = 5; %# define n here so that you need to change it only once 
color = hsv(nPlots); %# define a colormap 
for k=1:nPlots; %# default step size is 1 
    y=k*sin(x); 
    plot(x,y,'Color',color(k,:)); 
end % /for-loop 
end % /test1 - not necessary, btw. 

編輯

你也可以做到這一點沒有一個循環,並繪製二維數組,建議由@Ofri

function test1 
figure 
x = 1:0.1:10; 
k = 1:5; 
%# create the array to plot using a bit of linear algebra 
plotData = sin(x)' * k; %'# every column is one k 
plot(x,plotData) 
+0

工作!非常感謝你,天才 – Amit 2010-08-29 20:44:39

+0

@Amit:很高興它工作得很好。我已經擴展了一下解決方案。 – Jonas 2010-08-29 22:22:54

4

另一種選擇是使用的事實情節可以接受矩陣,並將它們視爲多條線路拼湊在一起。

function test1 
    figure %# create a figure 
    x=1:0.1:10; 
    for k=1:1:5; 
     y(k,:)=k*sin(x); %# save the results in y, growing it by a row each iteration. 
    end %# for-loop 
    plot(x,y); %# plot all the lines together. 
end %# test1 
+0

很棒的建議! תודה! – Amit 2010-08-29 20:51:44

+0

這種方式幾乎是有利的,因爲它交替線的顏色以及!簡直太棒了。 – Amit 2010-08-29 20:54:26

+0

關於更多。如果要手動設置圖中的顏色,可以添加第三個參數圖(x,y,顏色)。顏色應該是'r'的紅色,'b'的藍色等,所以你可以通過定義一個顏色數組col = ['r','g','b','c ','m'],然後將col(k)作爲第三個參數添加到圖中。 – 2010-08-29 21:36:55