Problem with while loop and matrix size.

2 ビュー (過去 30 日間)
Paul Kwon
Paul Kwon 2016 年 2 月 15 日
編集済み: sam0037 2016 年 2 月 19 日
The while loop seems to only work for "20", but does not seem to apply to any of the other elements of the vector. I also get an error saying "Index exceeds matrix dimensions." What am I doing wrong?
% This function sorts the elements of a vector from the largest to the smallest.
A = [2 5 20 1 3];
for z = 1:(length(A)-1);
y = z;
while A(y) > A(y+1);
B = A(y);
A(y) = A(y+1)
A(y+1) = B
y = y + 1;
end
end
  1 件のコメント
KSSV
KSSV 2016 年 2 月 15 日
What you are planning to do actually? In the above code, in a loop y became 5. on adding one and calling the index in A i.e A(y+1) this equals to A(6). But length of A is only 5. How it can get sixth element?

サインインしてコメントする。

回答 (2 件)

sam0037
sam0037 2016 年 2 月 19 日
編集済み: sam0037 2016 年 2 月 19 日
Hi,
It seems you are trying to access A(6) i.e. the sixth element in the array A and hence MATLAB is throwing an error. This can be debugged using the MATLAB debugger. Set debug mode to stop when an error is encountered and display the element y just before the end of while loop. Use the following code:
dbstop if error % this will stop the code on error
A = [2 5 20 1 3];
for z = 1:(length(A)-1);
y = z;
while A(y) > A(y+1);
B = A(y);
A(y) = A(y+1)
A(y+1) = B
y = y + 1;
fprintf('val of y = %d\n',y); % print the y value
end
end
You will observe the value of y to be 5 when the error occurs. Hence in the next iteration of while loop, the code is trying to access A(y+1) i.e. A(6). As a result of which MATLAB throws the error 'Index exceeds matrix dimensions.'
Make changes to your code as per your objective.
To know about sorting functions in MATLAB, refer to the following link: http://www.mathworks.com/help/matlab/array-manipulation.html

Ashish Sheikh
Ashish Sheikh 2016 年 2 月 17 日
Just use inbuilt Sort function .

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by