What does A(2:4) = [ ] do if A is a 3x3 matrix?

조회 수: 6 (최근 30일)
Chrisbel Rueda
Chrisbel Rueda 2022년 5월 17일
댓글: John D'Errico 2022년 5월 17일
This is my original matrix:
And this is the result:
This is the code:
A= [5 17 61; 32 80 -44; -1 -11 -13]
A(2:4) = []
I don't understand what it does.

답변 (1개)

James Tursa
James Tursa 2022년 5월 17일
편집: James Tursa 2022년 5월 17일
This is linear indexing. Even though the variable is a 2D matrix, MATLAB allows you to index into it using only one index. The linear indexes are simply numbered 1-numel(variable) (1-9 in your case) as they are ordered in memory. MATLAB will delete the 2nd, 3rd, and 4th element of the variable and return the result as a 1D vector. Since MATLAB stores variables in column order, this means the 32, -1, and 17 values are deleted.
  댓글 수: 2
Steven Lord
Steven Lord 2022년 5월 17일
Yup. You can see this more clearly if you use linear indexing on the whole array.
A= [5 17 61; 32 80 -44; -1 -11 -13]
A = 3×3
5 17 61 32 80 -44 -1 -11 -13
B = A(1:end)
B = 1×9
5 32 -1 17 80 -11 61 -44 -13
John D'Errico
John D'Errico 2022년 5월 17일
Yes. remember that MATLAB effectively stores all arrays, 2-d, 3-d, etc. internally as just a list of elements. As well, it stores the shape of that array separately.
But when you access an array using just ONE argument, MATLAB sees you want it to index into the array, as if it were a vector! We can do that!
You have this:
A= [5 17 61; 32 80 -44; -1 -11 -13]
A = 3×3
5 17 61 32 80 -44 -1 -11 -13
But MATLAB stores that as a simple list of elements, plus the final shape. So if you did
A(:)
ans = 9×1
5 32 -1 17 80 -11 61 -44 -13
That returns the elements as a vector, IN THE ORDER THEY ARE STORED. Now if you access
A(2:4)
ans = 1×3
32 -1 17
it gives you only those elements. Finally, when you do this:
A(2:4) = []
A = 1×6
5 80 -11 61 -44 -13
That deletes the specific elements we chose, thus the 2nd, 3rd, and 4th elements. Since the result would now make no sense at all as an array, we get the result you observed.

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

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by