How to use max() command with variable output?

12 ビュー (過去 30 日間)
David Stanley
David Stanley 2017 年 10 月 4 日
回答済み: Walter Roberson 2017 年 10 月 4 日
Is there any way to use the max() command and get a variable to appear in the text or will a numerical value always be the output? Thanks!
  1 件のコメント
James Tursa
James Tursa 2017 年 10 月 4 日
Please post a small example showing the input(s) and desired output(s).

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

回答 (1 件)

Walter Roberson
Walter Roberson 2017 年 10 月 4 日
X = [2 8 4; 7 3 9]; Y = X + randi([-1 1],2,3);
[m,idx] = max(X,Y)
Error using max
MAX with two matrices to compare and two output arguments is not supported.
That was the only meaning I could come up with for "get a variable to appear": the hypothesis that you might be using the two-input version of max() and wanting to know, for each element of the output, whether the maximum came from the first variable or the second variable. If by some odd circumstance that is what you are trying to do, then:
m = max(X,Y);
vars = {'X', 'Y'};
mask = m == X;
which_one = cell(size(m));
which_one(mask) = vars(1);
which_one(~mask) = vars(2);
Now which_one is a cell array of character vectors with the entries reflecting whether the max was from X or Y.
Note: this particular implementation will return the first variable in the case that the two entries are equal. This particular implementation will return the second variable in the case that the two entries are both NaN. Both of those could be changed if you were to define the desired behavior for those situations.

カテゴリ

Help Center および File ExchangeOther Formats についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by