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?

21 visualizaciones (últimos 30 días)
a = [17,12,12,-6,0,14];
temp =0;
for i=1:length(a)
if a(i)>a(i+1)
temp=a(i);
a(i)=a(i+1);
a(i+1)=temp;
end
end
disp(a)
I am getting an 'Index exceeds matrix dimensions error' in line 4

Respuestas (2)

Walter Roberson
Walter Roberson el 6 de Ag. de 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 el 6 de Ag. de 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:

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by