How to use max() command with variable output?

12 vues (au cours des 30 derniers jours)
David Stanley
David Stanley le 4 Oct 2017
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 commentaire
James Tursa
James Tursa le 4 Oct 2017
Please post a small example showing the input(s) and desired output(s).

Connectez-vous pour commenter.

Réponses (1)

Walter Roberson
Walter Roberson le 4 Oct 2017
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.

Community Treasure Hunt

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

Start Hunting!

Translated by