Finding and reporting the variable (Single number) of several with the largest value

1 view (last 30 days)
I need to find the variable name corresponding to the largest value in a set of variables.
My input variables look like:
A = 0.0076
B = 0.46
C = 0.05
And my desired output is
greatestValue = B
So far I have tried:
greatestValue = max([A B C]) %But this provides output 0.46 rather than B
and:
greatestNumber = max([A B C])
if greatestNumber == A
greatestValue = "A"
elseif greatestNumber == B
greatestValue = "B"
elseif greatestNumber == C
greatestValue = "C"
end
%This method successfully outputs "greatestValue = B"
% but it feels like overkill for what I assume there's
% a much more concise method
I think I've had a look around the forum and couldn't find anything, but I'm new to this so probably don't know where to look. Any solution, direction or other help would be appreciated.
Cheers.

Answers (3)

Alan Stevens
Alan Stevens on 5 May 2021
Here's one possibility
ABC = [0.0076, 0.46, 0.05];
abc = ['A','B','C'];
greatestValue = abc(ABC==max(ABC))
greatestValue = 'B'

Stephen23
Stephen23 on 5 May 2021
The MATLAB approach is to use vectors/matrices (which is where the name MATLAB comes from):
V = [0.0076,0.46,0.05];
C = ["A","B","C"];
[~,X] = max(V);
C(X)
ans = "B"

Arun Sanap
Arun Sanap on 5 May 2021
Hi Alexander,
I believe that there is no direct way to get the variable name from the max function, but there is a function called "inputname" that will return the name of a variable that was input into a function:
By using this, you can create a function that will return the name and value of the variable with the largest value, as given in the following example.
function [value, name] = getMaxNumber(varargin)
inputNumbers = [varargin{:}];
[value, index] = max(inputNumbers);
name = inputname(index);
end
The function "getMaxNumber" can be used as given below.
>> A = 1;
>> B = 2;
>> C = 3;
>>[value, name] = getMaxNumber(A, B, C)
It returns the following outputs.
value = 3
name = 'C'
I hope it helps.

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!