How do I sort entire columns of an array by a specific row?
2 views (last 30 days)
Show older comments
I have this code that finds the distance of points in space, defined by an array, from the origin and adds that distance to an existing array as a fourth column. I need to sort the columns (as in the entire column) of the output array by the values in this fourth row in ascending order. How do I do this? My code so far is
B=[]; n=1:20;
for col=1: length(A(3,n))
dist=sqrt((A(1,n)).^2+(A(2,n)).^2+(A(3,n)).^2);
B=[A(1,n); A(2,n); A(3,n); dist];
end
end
1 Comment
Answers (2)
Stephen23
on 9 Feb 2018
Edited: Stephen23
on 9 Feb 2018
@Elias Beaini: your code does not make much sense, and should be revised. For example:
- You define n=1:20, which means that A(3,n) will either throw an error or return 20 elements of A, in which case length(A(3,n)) will be 20. This is an overly complex way to simply get the value 20 (which you already know from how you defined n anyway). Avoid this complication.
- You try to expand B on each loop iteration (but actually don't: see below), but continually expanding array is inefficient. You should preallocate B before the loop, which is trivial to do because you know how many iterations there are and hence the final size of B.
- You do not use the loop variable col anywhere inside the loop.
- Inside the loop every dist calculation is exactly the same, and will produce exactly the same output.
- You do not concatenate, use indexing, use col, or in any other way try to collect these results, so all of them will be discarded apart from the last one.
Thus so far your code is simply equivalent to this:
n = 1:20;
B = sqrt((A(1,n)).^2+(A(2,n)).^2+(A(3,n)).^2);
I doubt that you need a loop at all:
n = 1:20;
B = sqrt(A(1,n).^2 + A(2,n).^2 + A(3,n).^2);
C = sortrows([A;B].', 4).'
1 Comment
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!