簡體   English   中英

循環內的循環

[英]A loop inside a loop

我在最后一年的項目中使用了MATLAB。 我正在求解一個幾何序列,例如x ^ j的和,從j = 0到n-1。 到目前為止,我有以下代碼:

$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值。 為此可以在循環內進行循環嗎? 例如,將N聲明為向量,然后使用我目前在其中的for循環?

此代碼適用於字符串輸入-

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM