Sortrows alternative / matrix sorting
이전 댓글 표시
I am trying to make a function to order a 2 row matrix by the top row so that the second row follows the first one. But i am unsure of how to do this. For the challenge i am trying to complete I am not allowed to use the in built sort function.
An example of this is:
INPUT
time = [ 1 3 2 4 7];
signal= [12 14 11 13 16];
Then the function would put this into a 2 row vector it would then be ordered and the output would be:
time_sorted = [ 1 2 3 4 7];
signal_sorted= [12 11 14 13 16];
This is my attempt at this but it isnt working.
Thank you
function [time_sorted,signal_sorted] = mysortdata(time,signal)
%make sure we have more than one element
if numel(time) <= 1
return
end
timeSignal = [time;signal];
%Picking the end of time to be a place where time is split in two
PivotTime = timeSignal(end);
% Removes this point from time
timeSignal(:,end) = [];
%create 4 arrays:
% LessTime/LessSignal: values in the array less than the pivot
% MoreTime/MoreSignal: values in the array greater than the pivot
LessTime = time(time <= PivotTime);
MoreTime = time(time > PivotTime);
LessSignal = time(time <= PivotTime);
MoreSignal = time(time > PivotTime);
% input Less and More into this function again
Less = mysortdata(LessTime,LessSignal);
More = mysortdata(MoreTime,MoreSignal);
%Put time back together again
timeSignal(1,:) = [Less, PivotTime, More];
time_sorted = timeSignal(1,:);
signal_sorted = timeSignal(2,:);
return
end
채택된 답변
추가 답변 (1개)
Bob Thompson
2018년 12월 12일
편집: Bob Thompson
2018년 12월 12일
0 개 추천
I know it may not be the fastest method, but what about using a loop to sort each element. Because you have 'time' and a piece of corresponding data I'm assuming you will always have positive time values, so for each loop you can just pull out the column with the minimum time value into a new matrix, and then remove the column from the original, until you have the whole array sorted.
timesignal = [time;signal];
for i = 1:length(time);
[value,index] = min(timesignal(1,:));
sorted(:,i) = timesignal(:,index);
if index == 1
timesignal = timesignal(:,2:end);
elseif index == size(timesignal,2)
timesignal = timesignal(:,1:end);
else
timesignal = timesignal(:,[1:index-1,index+1:end]);
end
end
댓글 수: 5
Dan Page
2018년 12월 12일
Bob Thompson
2018년 12월 12일
I'm not sure how you're getting that. I did catch one mistake I made with the if conditions, but my results with the test sample you gave came out as you indicate your results should.
Dan Page
2018년 12월 12일
Bob Thompson
2018년 12월 13일
편집: Bob Thompson
2018년 12월 13일
Are you using just the code I posted, or did you combine it with something else? That looks like what I would expect, for that particular set of numbers. Did you want them in a different order?
Dan Page
2018년 12월 13일
카테고리
도움말 센터 및 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!