Accumarray help: extracting matrix min/max based on values in first column.

3 ビュー (過去 30 日間)
Evan Watts
Evan Watts 2018 年 4 月 24 日
コメント済み: Evan Watts 2018 年 4 月 25 日
I have a matrix of 44222x4 with columns of date, time, flow, and pH respectively. I was trying to use accumarray to sort the min and max pH values for each date. My code is C=accumarray(matrix(:,1),(matrix(:,4),[],@(n){n}).
One of the large problems I have is with accumarray not accepting my matrix(:,4) as a numeric vector. Error text: "Second input VAL must be a full numeric, logical, or char vector or scalar."

採用された回答

Razvan Carbunescu
Razvan Carbunescu 2018 年 4 月 25 日
For this case the type of the data is probably what is giving you the problem.
In R2018a you can use groupsummary to get these results, if you put the data into a table:
T = array2table(matrix,'VariableNames',{'date', 'time', 'flow', 'pH'});
GT = groupsummary(T,'date',{'min', 'max'},'pH');
If using an earlier release can probably use findgroups / splitapply for the workflow:
[idx,dates] = findgroups(matrix(:,1));
min_pH = splitapply(@min,matrix(:,4),idx);
max_pH = splitapply(@max,matrix(:,4),idx);

その他の回答 (1 件)

Stephen23
Stephen23 2018 年 4 月 24 日
Why not just calculate the min/max directly using accumarray?:
[~,~,idx] = unique(matrix(:,1));
accumarray(idx,matrix(:,4),[],@min)
accumarray(idx,matrix(:,4),[],@max)
  3 件のコメント
Stephen23
Stephen23 2018 年 4 月 25 日
編集済み: Stephen23 2018 年 4 月 25 日

@Evan Watts: you have not told us what class matrix is, but I suspect that it might be a cell array, in which case you will need to convert it to a numeric array before using accumarray. How to convert it depends on how the data is stored inside it: as char vectors, or a numeric values:

vec = str2double(matrix(:,4)); % char vectors
vec = cell2mat(matrix(:,4));   % numeric scalars

If you do not have a cell array then you need to tell us what the class is:

class(matrix)
Evan Watts
Evan Watts 2018 年 4 月 25 日
Thanks! I with both of the answers here I was able to get it to work.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by