Saving for loop output in an array

84 ビュー (過去 30 日間)
Terry
Terry 2013 年 10 月 17 日
コメント済み: yamen alharbi 2020 年 12 月 29 日
I wrote a code in which I predefine the variable "a" and then set up a for loop of 5 iterations where the variable "a" goes through some basic operations. However, the for loop output only saves the fifth iteration of "a." How do I save all 5 iterations in a 1x5 array?
The code is as follows:
a = 10;
k = 0.5;
n = 2;
for m = 1:5
a = a + (a*k) + n;
end

採用された回答

Yatin
Yatin 2013 年 10 月 17 日
Hi,
You will have to insert the value of a in another array during each iteration. Below is the modified code:
a = 10;
k = 0.5;
n = 2;
valueOfA = zeros(1,5);
for m = 1:5
a = a + (a*k) + n;
valueOfA(m) = a;
end
  6 件のコメント
mohammed magdy
mohammed magdy 2019 年 12 月 1 日
thank you sir
yamen alharbi
yamen alharbi 2020 年 12 月 29 日
clc
clear all
a(1)=10; k=0.5;n=2;
a1=zeros(1,5); %create an array to store the results
for m=1:5
a(m+1)=a(m)+a(m)*k+n;
a1(1,m)=a(m+1); %store each result in a vector
end

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

その他の回答 (1 件)

Vivek Selvam
Vivek Selvam 2013 年 10 月 17 日
Terry, this implementation has a different final value.
a(m+1) = a(m) + a(m)*k + n;
Do you want the same final value?
If you are interested check out preallocation:

カテゴリ

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