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
0 件のコメント
回答 (2 件)
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
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:
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Shifting and Sorting Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!