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

3 views (last 30 days)
Chrisbel Rueda
Chrisbel Rueda on 17 May 2022
Commented: John D'Errico on 17 May 2022
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.

Answers (1)

James Tursa
James Tursa on 17 May 2022
Edited: James Tursa on 17 May 2022
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 Comments
John D'Errico
John D'Errico on 17 May 2022
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.

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!