Get back variables out of function inside a for loop

1 回表示 (過去 30 日間)
Enzo
Enzo 2022 年 12 月 9 日
回答済み: Dyuman Joshi 2022 年 12 月 9 日
Hello everyone,
I have extracted the values stored in 2 different matrices and used them in order to create a line (plot). One point is always the same (I1,M1) where I1 is the x coordinate and M1 is the Y.
inside J and WZ matrices, I have, let's say, 3 values each (but they could be more or less) and I have used them in order to create 3 different lines with one point constant (I1, M1) while the others change. PLease note that, I have added 2500 to all the values stored inside WZ.
Running the for loop, ends up in having created a slope matrix, with 3 values inside, which reprenset 3 different slopes. I have found the minimun value among them (-0.0168), and now, I would like to getting back from that value (the minimum), and to call back the corresponding WZ and J values associated
J = [2.5 27 56];
WZ = [12.2 23.2 33];
M1 = 22
M1 = 22
I1 = 2600
I1 = 2600
for ii = 1:numel(WZ)
slope(ii) = (J(ii)-M1)/(WZ(ii)+3750-I1);
slope_1 = min(slope);
end
disp(slope_1)
-0.0168
-0.0168 0.0043 0.0287
  2 件のコメント
Stephen23
Stephen23 2022 年 12 月 9 日
The simpler MATLAB approach is to write vectorized code and use the second output from MIN():
J = [2.5,27,56];
WZ = [12.2,23.2,33];
M1 = 22;
I1 = 2600;
slope = (J-M1)./(WZ+3750-I1);
[slope_1,idx] = min(slope);
WZ_1 = WZ(idx)
WZ_1 = 12.2000
J_1 = J(idx)
J_1 = 2.5000
Enzo
Enzo 2022 年 12 月 9 日
@Stephen23 yes, it works even better. Thanks a lot

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

採用された回答

Alan Stevens
Alan Stevens 2022 年 12 月 9 日
Here's one way
J = [2.5 27 56];
WZ = [12.2 23.2 33];
M1 = 22;
I1 = 2600;
for ii = 1:numel(WZ)
slope(ii) = (J(ii)-M1)/(WZ(ii)+3750-I1);
slope_1 = min(slope);
end
disp(slope_1)
-0.0168
indx = find(slope==slope_1)
indx = 1
WZ_1 = WZ(indx)
WZ_1 = 12.2000
J_1 = J(indx)
J_1 = 2.5000
  2 件のコメント
Enzo
Enzo 2022 年 12 月 9 日
@Alan Stevens you are the man! thanks so much
Stephen23
Stephen23 2022 年 12 月 9 日
Using the second output from MIN() is simpler than calling superfluous FIND().

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

その他の回答 (1 件)

Dyuman Joshi
Dyuman Joshi 2022 年 12 月 9 日
J = [2.5 27 56];
WZ = [12.2 23.2 33];
M1 = 22;
I1 = 2600;
slope=(J-M1)./(WZ+3750-I1)
slope = 1×3
-0.0168 0.0043 0.0287
[minval,minid]=min(slope)
minval = -0.0168
minid = 1
Jval=J(minid)
Jval = 2.5000
WZval=WZ(minid)
WZval = 12.2000

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by