Finding and reporting the variable (Single number) of several with the largest value
1 view (last 30 days)
Show older comments
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.
0 Comments
Answers (3)
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))
1 Comment
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)
0 Comments
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.
1 Comment
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!