Why i get problems with index arrays although it seems to have correct Input?
1 回表示 (過去 30 日間)
古いコメントを表示
hi,
I use a for loop to calculate some Values (MP1,MP2,MP3) from a matrix.
This is the code:
for x = 1:length(Matrix)
MP1(x) = Matrix(x,2)/Matrix(x,3);
MP2(x) = Matrix(x,4)/Matrix(x,5);
MP3(x) = Matrix(x,2)/Matrix(x,9);
end
I'm confused because i thought that if i use x = 1:length(Matrix) the for loop should work for every "Matrix" i want and will use the length of the specific Matrix.
But i get the error message "Index in position 1 exceeds array bounds (must not exceed 3)."
The Matrix in this particular case has a 3x13 double character. If i set a breakpoint at the "end" of this for loop and run it step by step its successfull for x = {1,2,3} but this for loop doesnt stops at x = 3 (as it should, if i give him x=1:length(Matrix) with a 3x13 double Matrix, am i right?).
Thanks for help!
1 件のコメント
採用された回答
Steven Lord
2022 年 3 月 23 日
What's the length of your 3-by-13 matrix?
A = ones(3, 13);
numRows = length(A) % ? This is the correct answer, but not what you want!
As stated in the documentation the length of an array is either 0 (if the array is empty) or the maximum value in the vector returned by the size function. If you specifically want the number of rows use either size with the dim input or the height function.
numRows = size(A, 1) % Correct
numRows = height(A) % Correct
その他の回答 (1 件)
Voss
2022 年 3 月 23 日
length(A) is the size of the array A in its longest dimension, so length(Matrix) in this case is 13, not 3.
You should use size(Matrix,1), which is the size of Matrix along the first dimension (i.e., size(Matrix,1) is the number of rows of Matrix).
for x = 1:size(Matrix,1)
MP1(x) = Matrix(x,2)/Matrix(x,3);
MP2(x) = Matrix(x,4)/Matrix(x,5);
MP3(x) = Matrix(x,2)/Matrix(x,9);
end
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!