Arrange (array of 9 numbers) in ascending order. (no sort)

11 views (last 30 days)
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

Answers (2)

Honglei Chen
Honglei Chen on 19 Sep 2012
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
  1 Comment
Aviroop Dutt Mazumder
Aviroop Dutt Mazumder on 21 Sep 2012
Thanks Honglei, I used the bubble command to get the number output in an ascending order

Sign in to comment.


Jan
Jan on 22 Sep 2012
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 Comments

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!