Filter löschen
Filter löschen

Why i get problems with index arrays although it seems to have correct Input?

1 Ansicht (letzte 30 Tage)
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);
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!

Akzeptierte Antwort

Steven Lord
Steven Lord am 23 Mär. 2022
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!
numRows = 13
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 = 3
numRows = height(A) % Correct
numRows = 3

Weitere Antworten (1)

Voss am 23 Mär. 2022
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);


Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange




Community Treasure Hunt

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

Start Hunting!

Translated by