How do you create an array with multiple rows in one line?

9 vues (au cours des 30 derniers jours)
Perplumblewintz
Perplumblewintz le 17 Déc 2020
Commenté : Cris LaPierre le 17 Déc 2020
I'm struggling with something that seems like it should be very simple. I'm trying to create an array of 3x3 matrices. I see that I can do something like:
A = [1,2,3; 4,5,6; 7,8,9]
A(:,:,2) = [9,8,7; 6,5,4; 3,2,1]
How do I do that in one line? I thought that something like this would work:
A = [[1,2,3; 4,5,6; 7,8,9]; [9,8,7; 6,5,4; 3,2,1]]
But that creates a 6x3 matrix. And this creates a 3x6 matrix:
A = [[1,2,3; 4,5,6; 7,8,9] [9,8,7; 6,5,4; 3,2,1]]
I've tried other variations and read documentation, but am at a loss here. Any help would be appreciated. Thanks!

Réponse acceptée

Cris LaPierre
Cris LaPierre le 17 Déc 2020
Modifié(e) : Cris LaPierre le 17 Déc 2020
I'm not aware of a shorthand way to do this. You can consult the documentation here.
One way could be to use reshape followed by a transpose. Not sure that really buys you anything, though.
A = pagetranspose(reshape([1,2,3, 4,5,6, 7,8,9, 9,8,7, 6,5,4, 3,2,1],3,3,2))
A =
A(:,:,1) = 1 2 3 4 5 6 7 8 9 A(:,:,2) = 9 8 7 6 5 4 3 2 1
Another option is to use cat to combine the two matrices in the 3rd dimension.
A2 = cat(3,[1,2,3; 4,5,6; 7,8,9], [9,8,7; 6,5,4; 3,2,1])
A2 =
A2(:,:,1) = 1 2 3 4 5 6 7 8 9 A2(:,:,2) = 9 8 7 6 5 4 3 2 1
  2 commentaires
Perplumblewintz
Perplumblewintz le 17 Déc 2020
Oh, wow. Okay, I guess I mmight be thinking about this wrong for matlab (as a programmer) :)
Thanks!
Cris LaPierre
Cris LaPierre le 17 Déc 2020
It's just a matter of learning what is possible. There are shortcuts for creating 1D and 2D arrays, but not 3D.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by