Finding and reporting the variable (Single number) of several with the largest value
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (3)
Alan Stevens
el 5 de Mayo de 2021
Here's one possibility
ABC = [0.0076, 0.46, 0.05];
abc = ['A','B','C'];
greatestValue = abc(ABC==max(ABC))
1 comentario
Stephen23
el 5 de Mayo de 2021
Note that
['A','B','C']
is just a complex way of writing
'ABC'
Stephen23
el 5 de Mayo de 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 comentarios
Arun Sanap
el 5 de Mayo de 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 comentario
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!