Is it possible to realize such loop in MATLAB?

1 回表示 (過去 30 日間)
Oscar
Oscar 2024 年 9 月 16 日
コメント済み: Voss 2024 年 9 月 16 日
Good day, everyone!
For example, we have some x variable.
Is it possible to realize such loop (using "for") to get these results?
1-st iteration: x-1
2-nd iteration: (x-1)*(x-2)
3-rd iteration: (x-1)*(x-2)*(x-3)
etc.

採用された回答

Voss
Voss 2024 年 9 月 16 日
x = 10;
n_iterations = 5;
results = zeros(1,n_iterations);
r = 1;
for ii = 1:n_iterations
r = r*(x-ii);
results(ii) = r;
end
results
results = 1×5
9 72 504 3024 15120
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Or, without the loop:
results = cumprod(x-(1:n_iterations))
results = 1×5
9 72 504 3024 15120
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  2 件のコメント
Oscar
Oscar 2024 年 9 月 16 日
Thank you very much!
Voss
Voss 2024 年 9 月 16 日
You're welcome!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by