Arrange (array of 9 numbers) in ascending order. (no sort)
11 次查看(过去 30 天)
显示 更早的评论
Please suggest me to find a commnad using for loop to Arrange (array of 9 numbers) in ascending order without using sort command. I used the following one, which didn't work
A = [4 16 36 64 1 9 25 49 81] B = [] for i = 1:9
B(i) = max(A)
find max(A)== 0
end
回答(2 个)
Honglei Chen
2012-9-19
You can do
B = unique(A)
But seriously, are you trying to implement a sort algorithm in MATLAB? If so, there are many algorithms available, e.g., quick sort
Jan
2012-9-22
Improvement of your method:
A = [4 16 36 64 1 9 25 49 81];
B = zeros(1, 9); % Pre-allocate!
for ii = 1:9
[value, index] = max(A);
B(ii) = value;
A(index) = -Inf;
end
For 9 elements an insert-sort would be fine also.
6 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!