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

2 Ansichten (letzte 30 Tage)
Tim K am 23 Mär. 2022
Kommentiert: Voss am 23 Mär. 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 KommentarKeine anzeigenKeine ausblenden
Arif Hoq am 23 Mär. 2022
what is size of Matrix ? can you please attch your data ?

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

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
1 KommentarKeine anzeigenKeine ausblenden
Tim K am 23 Mär. 2022
Thank you very much!
This helps a lot!

Melden Sie sich an, um zu kommentieren.

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);
end
2 Kommentare1 älteren Kommentar anzeigen1 älteren Kommentar ausblenden
Voss am 23 Mär. 2022
You're welcome!

Melden Sie sich an, um zu kommentieren.

Kategorien

Find more on Matrix Indexing in Help Center and File Exchange

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by