How to modify values in an array at a certain point inside a loop?

조회 수: 9 (최근 30일)
Rabia Zulfiqar
Rabia Zulfiqar 2020년 6월 30일
댓글: darova 2020년 7월 1일
I have formed this simple code
clc
clear all
a=1.4
for i=1:10 %Here i represents years
A(:,:,i)=a; %For storing the values in 3D matrix
a = a * 0.9;
end
The answer I am getting is
val(:,:,1) =
1.4000
val(:,:,2) =
1.2600
val(:,:,3) =
1.1340
val(:,:,4) =
1.0206
val(:,:,5) =
0.9185
val(:,:,6) =
0.8267
val(:,:,7) =
0.7440
val(:,:,8) =
0.6696
val(:,:,9) =
0.6027
val(:,:,10) =
0.5424
I want to modify my code such that when the value of 'a' becomes less than a<0.6*1.4 so for that year 'a' should be 1.4 again.Like in this case in year 6 the value is 0.8267 which is less than 0.6*1.4 so val(:,:,6) should become 1.4 and then again the 'a' will be calculated as per defined equation.I mean I want my answer like this and also I want the year in which the value becomes 1.4 again like here in this case the year is 6.How can I modify my code in order to get this answer?Kindly help me
Desired Answer:
val(:,:,1) =
1.4000
val(:,:,2) =
1.2600
val(:,:,3) =
1.1340
val(:,:,4) =
1.0206
val(:,:,5) =
0.9185
val(:,:,6) =
1.4000
val(:,:,7) =
1.2600
val(:,:,8) =
1.1340
val(:,:,9) =
1.0206
val(:,:,10) =
0.9185

채택된 답변

darova
darova 2020년 6월 30일
Just add if condition inside your for loop
clc
clear all
a=1.4
for i=1:10 %Here i represents years
A(:,:,i)=a; %For storing the values in 3D matrix
a = a * 0.9;
if a < 1.4*0.6
a = 1.4;
end
end
  댓글 수: 2
Rabia Zulfiqar
Rabia Zulfiqar 2020년 6월 30일
Thankyou so much for your help dear. Can you also please idntify that how would I know the year where this replcament has been done?
For instance I know that I can do something like this
b=find(A==1.4);
B=b(2);
and then B should be equal to 6 but is there any other way to find this year?
darova
darova 2020년 7월 1일
You are doing ok, It's the right wayt to find the year. Why do you want another method?
The only thing: use some tolerance since you have float numbers
Find
ind = find(abs(A-1.4)<0.01);
B = b(ind);

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by