2014-02-26 59 views
-1

我正在使用MATLAB作爲我的最後一年項目的一部分。我正在求解一個幾何級數,如從j = 0到n-1的x^j的總和。我有以下代碼至今:循環內的循環

$Variable dictionary 
%N Number of terms to sum 
%alpha Sum of series 
%x Vector of constants 
%n Loop counter 

N = input('Enter the number of terms to sum: '); 
alpha = 0; 
x = [0.9 0.99 0.999 0.9999 0.99999 0.999999]; 
for n = 0:N-1 
alpha = alpha + (x.^(n)); 
end 
format long 
alpha 

我希望能夠把的n值在自己和能夠輸入比n值更。是否有可能在這個循環內做一個循環?例如declare N作爲一個向量,然後使用for循環,我現在有它嗎?

回答

2

該代碼將與字符串輸入工作 -

代碼
N = input('Enter the number of terms to sum: '); 
N = str2num(N); 

其餘部分保持不變。

輸入輸入作爲一個字符串,即作爲一個例子 -

Enter the number of terms to sum: '2 5 8 11 14 17' 
+0

三江源此但是當我修改我的代碼其唯一的投擲值對於n = 10? – user12428

+0

你能用修改後的代碼編輯你的問題嗎? – Divakar