Why can we write A(1,2) for a nx2 matrix, with n>1, and we cannot write i=1; x(i,2) for a vector x = [x1 x2]?
It only accepts x(i+1), but I need to iterate the index i over the rows and not the columns, for any nx2 matrix with n>=1.
Thank you in advance.

 채택된 답변

dpb
dpb 2025년 11월 12일

1 개 추천

There's nothing preventing addressing a row vector by its row, column indices...
x=1:3;
for i1=1:height(x)
for j1=1:width(x)
disp([i1 j1 x(i1,j1)])
end
end
1 1 1 1 2 2 1 3 3
One only gets in trouble when trying to go outside array bounds...
x(2,1)
Index in position 1 exceeds array bounds. Index must not exceed 1.

댓글 수: 4

Luisa
Luisa 2025년 11월 12일
Thank you. Maybe I am doing wrong elsewhere.
dpb
dpb 2025년 11월 12일
편집: dpb 2025년 11월 12일
A common oversight in a looping construct is to have an "I+1" reference in a loop that counts i to the size in the given dimension. That will end up addressing outside the array bounds when it reaches the end.
Another possibility in your case would be if the expected row vector were a column vector instead by an inadvertent change in orientation.
There are many other possibilities as well that lead to a similar result, of course, but that's the sort of thing to look for.
Set a breakpoint on error and it will stop when the error occurs and you can then look at where you are and what are the values of various things that affect the indices and discover the source of the logic error...
Luisa
Luisa 2025년 11월 12일
편집: Luisa 2025년 11월 12일
Yes, I had made a syntax error in the code in another place, and it contested as "Index in position 1 exceeds array bounds. Index must not exceed 1."
Thank you so much.
dpb
dpb 2025년 11월 12일
Glad to help and that you found it...enjoy!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2025년 11월 12일

0 개 추천

i = 1;
x = [10, 20]
x = 1×2
10 20
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
x(i, 2) % Display second column of first (and only) row of a row vector.
ans = 20
I'm not seeing the problem. It works. You must be describing something different than your actual code.
Contrary to what you said, it will not accept x(i+1, 2), which is x(2,2), because there is no second row of x. Remember row is the first index and column is the second index.
I encourage you to use descriptive names like row and col instead of i and j when using indexes in arrays. It will avoid a lot of mistakes.

댓글 수: 1

Luisa
Luisa 2025년 11월 12일
Thank you, I had made a syntax error in the code in another place.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2025년 11월 12일

댓글:

dpb
2025년 11월 12일

Community Treasure Hunt

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

Start Hunting!

Translated by