in a matrix (a val output from sort): sort first column based on whether the numbers in the second column are the same

4 次查看(过去 30 天)
Here is what I have:
[Pos, num] = MyFun(handles);
%Pos is a i x 2 (the # of rows changes size every session) (row = x and y coords)
num is a i x 1 (row also changes)
[val, idx] =sort(num,1,'descend');
for i = 1:size(Pos,1)
new_Pos(i,:) = Pos((idx(i,1)),:);
end
So, as you can see, I have taken my output, sorted it based on value, used the index of the sort function to rearrange my Pos matrix so that it is descending based on the number associated with it (the number is the output from MyFun).
Now, what I need to do is, in addition to sorting Pos by the number associated with it, I also need to sort it by the distance between,for example, Pos(1,:) and Pos(2,:) and so on until Pos(end-1,:) and Pos(end,:). The distance only matters for Positions that have the same 'num' value. So, I need to sort a matrix that changes each session. I only need to sort the first columns of rows that have the same number for their second column: for example: a matrix of column 1 = dist between positions and the column 2 = num
1 4
3 4
1 4
2 5
3 5
1 5
%So I need to sort that so it looks like this:
1 4
1 4
3 4
1 5
2 5
3 5
I have attempted to do this but I am stumped ...
val_dist = [];
k = size(val,1);
for i = 1:(k-1)
if val(i,1) == val(i+1,1)
val_dist = [sqrt([PosXYZ(idx(i,1),1) - PosXYZ(idx(i+1,1),1)]^2 + [PosXYZ(idx(i,1),2) - PosXYZ(idx(i+1,1),2)]^2), val(i,1); val_dist ];
end
end
n=[];
n_save = [];
for i = 1: (size(val_dist)-1)
while val_dist(i,2) == val_dist(i+1,2)
n = [n; val_dist(i+1,1)];
[n_val n_idx] = sort(n,1);
n_save = [n_save; n_val, n_idx];
end
end

采纳的回答

Sean de Wolski
Sean de Wolski 2011-6-23
sortrows(pos, [2 1])

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by