Why i get problems with index arrays although it seems to have correct Input?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Tim K
el 23 de Mzo. de 2022
Comentada: Voss
el 23 de Mzo. de 2022
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 comentario
Respuesta aceptada
Steven Lord
el 23 de Mzo. de 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!
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
Más respuestas (1)
Voss
el 23 de Mzo. de 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);
end
2 comentarios
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!