MATLAB Answers

Problem with while loop and matrix size.

9 views (last 30 days)
Paul Kwon
Paul Kwon on 15 Feb 2016
Edited: sam0037 on 19 Feb 2016
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 Comment

KSSV
KSSV on 15 Feb 2016
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?

Sign in to comment.

Answers (2)

sam0037
sam0037 on 19 Feb 2016
Edited: sam0037 on 19 Feb 2016
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

  0 Comments

Sign in to comment.


Ashish Sheikh
Ashish Sheikh on 17 Feb 2016
Just use inbuilt Sort function .

  0 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!