在MATLAB中查找分配给特定字符串的最大列数

在MATLAB中查找分配给特定字符串的最大列数,matlab,Matlab,假设我在MATLAB中有这样一个表: Location String Number 1 a 26 1 b 361 2 c 28 2 a 45 3 a 78 4 b 82 我想创建一个只返回3行的

假设我在MATLAB中有这样一个表:

Location     String      Number

1              a           26 
1              b           361  
2              c           28
2              a           45 
3              a           78
4              b           82
我想创建一个只返回3行的脚本,其中包含每个字符串的最大数字。因此,在本例中,返回的表如下所示:

Location    String     Number

3            a         78
1            b         361   
2            c         28

我想要处理的实际表要大得多,尽管我这样写是为了简单。关于如何完成这项任务有什么想法吗?提前感谢您抽出时间

您可以使用
splitapply
,每行使用
id
。 有关详细信息,请参阅评论

% Assign unique ID to each row
tbl.id = (1:size(tbl,1))';
% Get groups of the different strings
g = findgroups(tbl.String);
% create function which gets id of max within each group 
% f must take arguments corresponding to each splitapply table column
f = @(num,id) id(find(num == max(num), 1));
% Use splitapply to apply the function f to all different groups
idx = splitapply( f, tbl(:,{'Number','id'}), g );
% Collect rows
outTbl = tbl(idx, {'Location', 'String', 'Number'});

>> outTbl = 
   Location   String    Number
      3        'a'        78   
      1        'b'       361   
      2        'c'        28   
或者只是一个简单的循环。此循环仅覆盖
String
的唯一值,因此应该非常快

u = unique(tbl.String);
c = cell(numel(u), size(tbl,2));
for ii = 1:numel(u)
    temp = tbl(strcmp(tbl.String, u{ii}),:);
    [~, idx] = max(temp.Number);
    c(ii,:) = table2cell(temp(idx,:));
end
outTbl = cell2table(c, 'VariableNames', tbl.Properties.VariableNames);

我的想法是找到每个字符串的最大值

创建所有字符串的向量,并只包含一次。比如:

strs=['a','b','c']

然后创建一个向量,该向量将存储每个字符串的最大值:

n=length(strs);
max_values=zeros(1,n);
现在用整个数据的大小创建一个循环,将当前最大值与当前值进行比较,如果
current\u value>max\u value
,则进行替换:

for i=1:your_table_size
   m=find(strs==current_table_string);   % This finds the index of max_values
   if max_values(m)<current_table_Number   % This the the i_th row table_number
      max_values(m)=current_table_Number;
   end
end
对于i=1:您的表大小
m=查找(strs==当前_表_字符串);%这将查找最大值的索引

如果max_值(m),则不会输出OP要求的内容,即每个类别的所有max行的表格。相反,它只输出每个类别的所有最大值的向量。谢谢你的评论@Wolfie。我主要是指找到所需脚本的想法,正如您所看到的,我并没有编写整个脚本。因此,是的,你是对的,但是我相信用表参数替换代码对OP来说并不难,只要他有这个想法。