kenes
kenes

Reputation: 133

sort structure with respect to its field MATLAB

I have a structure which contains location(-x -y coord.) and type information of points:

mystr(1).type = 'type2';
mystr(1).location = [5 7]; % [x y] = [5 7]
mystr(2).type = 'type1';
mystr(2).location = [2 8]; % [x y] = [2 8]

I have at least as much as 100 points. I want to sort mystr locations first with respect to -y coordinates, second -x coordinates in ascending orders. Last, I want mystr(1) to show the point which has the lowest locations and its type. Also, I want mystr(end) to show the point which has the highest locations and its type.

My code which sorts locations are below.

mystr(1).location = [5 7]; mystr(1).type = 'type2';
mystr(2).location = [2 8]; mystr(2).type = 'type1';
mystr(3).location = [3 9]; mystr(3).type = 'type1';
mystr(4).location = [4 2]; mystr(4).type = 'type2';
allpoints = [];
for i = 1:4
    allpoints = [allpoints; mystr(i).location];
end
[~,in] = sort(allpoints(:,2),1,'ascend');
[r,c] = size(allpoints);
allpoints = mat2cell(allpoints,r,2*ones(1));
allpoints = allpoints{1,1}(in,:)
[~,in] = sort(allpoints(:,1),1,'ascend');
[r,c] = size(allpoints);
allpoints = mat2cell(allpoints,r,2*ones(1));
allpoints = allpoints{1,1}(in,:)
for i = 1:4
    mystr(i).location = allpoints(i,:)
end

I could not do the types but locations will be like:

mystr(1).location = [2 8];
mystr(2).location = [3 9];
mystr(3).location = [4 2];
mystr(4).location = [5 7];

PS: I am also glad if anyone can shorten the sorting part. I think it is unnecessarily long. Thanks in advance.

Upvotes: 2

Views: 1628

Answers (2)

LowPolyCorgi
LowPolyCorgi

Reputation: 5171

Here is your anwer:

[~, I] = sortrows(cat(1,mystr(:).location),[2 1]);
mynewstr = mystr(I);

Best,

Upvotes: 2

Jonas
Jonas

Reputation: 74940

If you want to do sorting and filtering of values, then you may want to consider storing the values in a table.

However, assuming you're stuck with a structure, here is what you can do:

%# create n-by-2 array with locations
locations = cat(1,mystr.location);

%# sort ascending, so that x are sorted, and within equal x, y are sorted
[~,sortOrder] = sortrows(locations,[1 2]);

%# rearrange the structure
mystrSorted = mystr(sortOrder)

Note that this assumes that location is never empty; if that is possible, you need to first replace empty with [NaN NaN] to avoid a catastrophic mess-up.

Upvotes: 2

Related Questions