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일

10 개 추천

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

Terry
Terry 2013년 10월 17일
Thank you very much. This worked perfectly.
hamid meyal
hamid meyal 2015년 4월 12일
i also solved after reading this answer. thank you
Hi, I tried this way to solve my code, but it doesn't work. Could you help me?
t = 0:20000;
Vx1 = 1000;
A = zeros(1,20)
for ii = 1:2000:length(t)
Vx1= Vx1 - (0.0004*Vx1^2)*(t(ii)/1000)
A(ii)= Vx1;
end
Mir Toufikur  Rahman
Mir Toufikur Rahman 2016년 6월 30일
It helps very much. Thank you.
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일

1 개 추천

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:

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2013년 10월 17일

댓글:

2020년 12월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by