MATLAB Answers

I'm new to matlab and am trying to sort an array in ascending order without using the sort command. How would I rectify this?

1 view (last 30 days)
Sean Jose
Sean Jose on 6 Aug 2020
Answered: James Tursa on 6 Aug 2020
a = [17,12,12,-6,0,14];
temp =0;
for i=1:length(a)
if a(i)>a(i+1)
I am getting an 'Index exceeds matrix dimensions error' in line 4


Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 6 Aug 2020
You have
for i=1:length(a)
so i can be equal to length(a) . Then you do
if a(i)>a(i+1)
When i has become length(a) this test becomes
if a(length(a)) > a(length(a)+1)
In the case that a is a vector,a(length(a)+1) is indexing outside of a . You can only have a(length(a)+1) succeed in the case that a is not a vector

James Tursa
James Tursa on 6 Aug 2020
This is a "bubble sort" and you have two problems. First, as mentioned by Walter, is your indexing max value is one too big. You need to use length(a)-1 as the max index. Second problem is that you only make one pass through the data, which only exchanges elements by one spot. You need to make multiple passes through the data to get everything to bubble to the correct spot. In the worst case the first element would have to bubble down to the last spot which would take length(a)-1 passes. So your logic needs to be wrapped in another loop ... could be an outer for loop or an outer while loop. See the pseudo code here for an example of what this code should look like:


Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by