Finding maximum value and returning variable name of the column

8 ビュー (過去 30 日間)
Karel Starý
Karel Starý 2022 年 3 月 15 日
回答済み: Cris LaPierre 2022 年 3 月 15 日
Hello all!
Data:
A = [1;2;3;4];
B = [5;4;1;2];
C = [2;3;2;5];
T=table(A,B,C);
I would like to have a function that would check each row for the largest number and return the name of the collum where the max value was found. In this case, it should return: B,B,A,C
The table is just an example, I don't mind using cell arrays, tables or any other way how to work with the data.
Additional points: How to make sure that the function would return the character closest to A in case the largest numbers would occur multiple times in the same row?

採用された回答

Davide Masiello
Davide Masiello 2022 年 3 月 15 日
編集済み: Davide Masiello 2022 年 3 月 15 日
clear,clc
A = [1;2;3;4];
B = [5;4;1;2];
C = [2;3;2;5];
T=table(A,B,C);
[maxval,idx] = max(table2array(T),[],2);
T.Properties.VariableNames(idx)
ans = 1×4 cell array
{'B'} {'B'} {'A'} {'C'}
Regarding the additional point question, I think the max function will do that by default (i.e. it will return the first max value it finds on a specific row). Check this for instance:
clear,clc
A = [1;4;3;4];
B = [5;4;1;2];
C = [2;3;2;5];
T=table(A,B,C);
[maxval,idx] = max(table2array(T),[],2);
T.Properties.VariableNames(idx)
ans = 1×4 cell array
{'B'} {'A'} {'A'} {'C'}

その他の回答 (1 件)

Cris LaPierre
Cris LaPierre 2022 年 3 月 15 日
Look into finding the max along the second dimension, and have it return the loacation of the max.
However, max does not work with tables, so you will need to turn your table into an Array using table2array.
You can create a vector containting your table variable names. Use the index from max to extract the corresponding variable names.
varNames = T.Properties.VariableNames

カテゴリ

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

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by