How do I sort entire columns of an array by a specific row?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Respuestas (2)
Stephen23
el 9 de Feb. de 2018
Editada: Stephen23
el 9 de Feb. de 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 comentario
Abhishek Ballaney
el 9 de Feb. de 2018
https://in.mathworks.com/help/matlab/ref/sort.html
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!