MATLAB finding max. of a struct

Deadly 提交于 2019-12-11 02:04:45

问题


I am trying to find max value of a struct but max([tracks(:).matrix]) does not work. It gives me the following error: "Error using horzcat CAT arguments dimensions are not consistent." Do you have an idea?

Here is what my struct looks like:

tracks = 

1x110470 struct array with fields:
    nPoints
    matrix

tracks.matrix includes 3D points. For example here is

tracks(1,2).matrix:

33.727467   96.522331   27.964357
31.765503   95.983849   28.984663
30.677082   95.989578   29

回答1:


You can use array fun, followed by another max to do this:

s.x = [1 3 4];
s(2).x = [9 8];
s(3).x = [1];

maxVals = arrayfun(@(struct)max(struct.x(:)),s);

maxMaxVals = max(maxVals(:));

Or, if you want to retain the size of .x after MAX:

s.x = [1 3 4];
s(2).x = [9 8 3];
s(3).x = [1 2 2; 3 2 3];

maxVals = arrayfun(@(struct)max(struct.x,[],1),s,'uniformoutput',false);

maxMaxVals = max(cat(1,maxVals{:}))

Or, if you know everything is n x 3

s.x = [1 3 4];
s(2).x = [9 8 3];
s(3).x = [1 2 2; 3 2 3];
matrix = cat(1,s.x)
maxVals = max(matrix)



回答2:


Im not sure what you are trying to find the max of, but you can do this:

matrixConcat = [tracs.matrix]

which will give you a big concatenated list of all the matrices. You can then do max on that to find the maximum.

Let me know if this is what you were looking for otherwise i will change my answer.




回答3:


You can't use [] because the sizes of all tracks.matrix are different, hence the concatenation fails.

You can however use {} to concatenate to cell:

% example structure
t = struct(...
    'matrix', cellfun(@(x)rand( randi([1 5])), cell(1, 30), 'uni', 0))


% find the maximum of all these data    
M = max( cellfun(@(x)max(x(:)), {t.matrix}) );

Now, if you don't want to find the overall maximum, but the maximum per column (supposing you have (x,y,z) coordinates in each column, you should do

% example data
tracks = struct(...
    'matrix', {rand(2,3) rand(4,3)})

% compute column-wise max 
M = max( cat(1, tracks.matrix) )

This works because calling tracks.matrix when tracks is a multi-dimensional structure is equal to expanding the contents of a cell-array:

tracks.matrix         % call without capture equates to:

C = {tracks.matrix};  % create cell
C{:}                  % expand cell contents


来源:https://stackoverflow.com/questions/13575523/matlab-finding-max-of-a-struct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!