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 CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by