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

5 vues (au cours des 30 derniers jours)
Chrisbel Rueda
Chrisbel Rueda le 17 Mai 2022
Commenté : John D'Errico le 17 Mai 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.

Réponses (1)

James Tursa
James Tursa le 17 Mai 2022
Modifié(e) : James Tursa le 17 Mai 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 commentaires
Steven Lord
Steven Lord le 17 Mai 2022
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 le 17 Mai 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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by