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

15 次查看(过去 30 天)
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