how can i sort a matrix (all rows and columns are sorted) without using any special function like "sort"?
이전 댓글 표시
i guess it has to do something with "min" and "max" functions...
for example:
A = [2 3 4 5; 6 9 1 5]; %%%"A" can be of any size %%%
%%%B = sorted A %%%
min(A) = [2 3 1 5]; %%%1st unsorted row of B %%%
max(A) = [6 9 4 5]; %%%2nd unsorted row of B %%%
now i've to sort the rows...
any idea?
댓글 수: 2
John Petersen
2012년 12월 5일
Lots of ideas on this at
Babak
2012년 12월 5일
Matrix A you are providing only has 1 row. How can B have more than 1 row?
답변 (3개)
Jan
2012년 12월 6일
1 개 추천
This is a perfect question for an internet research:
or
If you don't want to use sort() then you can write your own sorting algorithm. Like this one (untested):
function B = mysortfunc(A)
if size(A,1)*size(A,2)~=length(A)
errordlg('enter a vector');
return
end
if size(A,2)~=1
A=A';
end
rem_A = A;
for j=1:length(A)
[value,index] = min(rem_A);
B(j) = value;
if index>1
A1 = rem_A(1:index-1);
else
A1=[];
end
if index<length(rem_A)
A2 = rem_A(index+1:end);
else
A2 = [];
end
rem_A = [A1 , A2]
end
댓글 수: 3
A simplification of your method with pre-allocation:
function B = mysortfunc(A)
A = A(:);
B = zeros(1, numel(A));
for ii = 1:numel(A)
[value, index] = min(A);
B(ii) = value;
A(index) = NaN;
end
However, the scientists have developped much better sorting methods in the last 1000 years. I do not assume that a teacher would be happy to see such a brute-force approach. Therefore I dare to publish this, although it solves a homework question, because submitting it as "solution" is a bad idea.
José-Luis
2012년 12월 7일
1000 years? Babbage would be impressed...
Jan
2012년 12월 9일
I'm convinced, that even the scroll of parchment in the Egypt libraries have been sorted with smarter methods 5000 years ago, but I cannot find any resources to prove this.
The optimal sorting machine is still the SFL (spaghetti fork lifter): Cut spaghetti noodles according to the values to be sorted. Lift them up and push them against a wall. The processing time does not depend on the number of elements and even the pre-processing is only O(n).
Pritesh Shah
2012년 12월 7일
Simple Solution A = [2 3 4 5; 6 9 1 5]
A =
2 3 4 5
6 9 1 5
>> sort(min(A))
ans =
1 2 3 5
댓글 수: 1
John Petersen
2012년 12월 7일
You used 'sort' which he specifically requested not to be used, and he also specified that A could be any size.
카테고리
도움말 센터 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!