Effacer les filtres
Effacer les filtres

Problem with while loop and matrix size.

2 vues (au cours des 30 derniers jours)
Paul Kwon
Paul Kwon le 15 Fév 2016
Modifié(e) : sam0037 le 19 Fév 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 commentaire
KSSV
KSSV le 15 Fév 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?

Connectez-vous pour commenter.

Réponses (2)

sam0037
sam0037 le 19 Fév 2016
Modifié(e) : sam0037 le 19 Fév 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

Ashish Sheikh
Ashish Sheikh le 17 Fév 2016
Just use inbuilt Sort function .

Catégories

En savoir plus sur Operators and Elementary Operations dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by