필터 지우기
필터 지우기

How do I sort entire columns of an array by a specific row?

조회 수: 2 (최근 30일)
Elias Beaini
Elias Beaini 2018년 2월 9일
편집: Stephen23 2018년 2월 9일
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

답변 (2개)

Stephen23
Stephen23 2018년 2월 9일
편집: Stephen23 2018년 2월 9일
@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
Guillaume
Guillaume 2018년 2월 9일
All of Stephen's comments are extremely relevant and should be heeded but just to make it clear, he also answered the question asked:
To sort according to the fourth column use sortrows (not sort)

댓글을 달려면 로그인하십시오.


Abhishek Ballaney
Abhishek Ballaney 2018년 2월 9일
https://in.mathworks.com/help/matlab/ref/sort.html

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by