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 次查看(过去 30 天)
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

回答(2 个)

Walter Roberson
Walter Roberson 2020-8-6
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 2020-8-6
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:

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by