Sorting Algorithm
3 ビュー (過去 30 日間)
古いコメントを表示
I need to take two arrays and sort one in ascending order, while carrying along the second one. I cannot use the sort function in Matlab.
ex) Array1 = [3,-1,-34,10,8] Array2 = [2,-9,4,-5,0]
0 件のコメント
回答 (4 件)
Sean de Wolski
2011 年 5 月 4 日
Then even better - trump your teacher with sortrows!
A = sortrows([array1(:),array2(:)]);
array1_sorted = A(:,1).';
array2_sorted = A(:,2).';
0 件のコメント
Andrei Bobrov
2011 年 5 月 5 日
more variant
Array1 = [3,-1,-34,10,8];
Array2 = [2,-9,4,-5,0];
A = [Array1;Array2];
SortedArray = [];
while ~isempty(A)
[~,I] = min(A(1,:));
A(:,[1 I]) = A(:,[I 1]);
SortedArray = [SortedArray A(:,1)];
A = A(:,2:end);
end
or
Array1 = [3,-1,-34,10,8];
Array2 = [2,-9,4,-5,0];
A = [Array1;Array2];
k = 1:length(A);
while ~isempty(k)
[~,I] = min(A(1,k));
A(:,[k(1) k(I)]) = A(:,[k(I) k(1)]);
k = k(2:end);
end
or
Array1 = [3,-1,-34,10,8];
Array2 = [2,-9,4,-5,0];
A = [Array1;Array2];
n = length(A);
for j = 1:n
k = j:n;
[~,I] = min(A(1,k));
A(:,[j k(I)]) = A(:,[k(I) j]);
end
condition without built-in sort functions. I think sortrows, sort and unique - sort function MATLAB
0 件のコメント
Matt Tearle
2011 年 5 月 4 日
In the spirit of Sean's answer... this works for the given example:
[~,idx] = unique(Array1);
Array2(idx)
EDIT (and may Cleve have mercy on my soul)
[s1,idx] = unique(Array1);
if numel(s1)<numel(Array1)
s2 = [];
for k=1:numel(s1)
s2 = [s2,Array2(s1(k)==Array1)];
end
else
s2 = Array2(idx);
end
s2
7 件のコメント
Matt Tearle
2011 年 5 月 5 日
a) Any particular error? Given that it works fine for me (R2011a), it's a bit hard for me to tell why you might be getting "an error".
b) I don't know why you can't use the sort function, but, whatever the reason, I doubt you can really use the unique function either. (Or sortrows)
b, part 2) Sean and I gave answers that technically didn't use sort, but are not good ways to solve the problem (unless there really is a reason you can use unique or sortrows, but not sort).
Daniel Shub
2011 年 5 月 5 日
I think the sortrows/unique answers may be cheating since they might call sort under the hood ... I am sure this student would not want to cheat. My solution uses both eval and feval, so should get extra credit.
Array1 = [3,-1,-34,10,8];
Array2 = [2,-9,4,-5,0];
while 42 > sqrt(pi)
eval('x = randperm(length(Array1));');
if feval('all', diff(Array1(x)) > 0)
return;
else
disp('MATLAB is stupid and guessed wrong!');
disp(['[', num2str(Array1(x)), '] is not sorted!']);
disp('Trying again!');
disp(' ');
end
end
Array1(x)
Array2(x)
Any concerns about inefficiencies are silly as the distributed computing toolbox would allow my answer to harness the power of a computer cluster.
0 件のコメント
参考
カテゴリ
Help Center および 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!