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 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