Problem with while loop and matrix size.
2 ビュー (過去 30 日間)
古いコメントを表示
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
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
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 more about debugging, refer to the following link: http://www.mathworks.com/help/releases/R2015b/matlab/matlab_prog/debugging-process-and-features.html
To know about sorting functions in MATLAB, refer to the following link: http://www.mathworks.com/help/matlab/array-manipulation.html
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Operators and Elementary Operations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!