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

olmpazwi  于 2023-04-21  发布在  Matlab
关注(0)|答案(2)|浏览(170)

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

Location     String      Number

1              a           26 
1              b           361  
2              c           28
2              a           45 
3              a           78
4              b           82

我想创建一个只返回3行的脚本,其中包括每个字符串的最大Number。因此,在这种情况下,返回的表将如下所示:

Location    String     Number

3            a         78
1            b         361   
2            c         28

我想要处理的实际表要大得多,尽管我这样写是为了简单。如何处理这个任务?

bf1o4zei

bf1o4zei1#

您可以使用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);
xu3bshqb

xu3bshqb2#

找到每个字符串的最大值我的想法是。
为所有字符串创建一个vector,并只包含一次。类似于:
strs=['a','b','c'];
然后创建一个vector来存储每个字符串的最大值:

n=length(strs);
max_values=zeros(1,n);

现在创建一个循环,将当前的max_value与当前值进行比较,并替换if current_value>max_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

相关问题