How to create a list of matrices??
49 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I would like to store 5 matrices into one list. As I am used to Python I am quite surprised that I can't do it in a simple and obvious way.
Is there a way for me to create a list L so that L(i) would return me a Matrice n*n ?
L=((n*n),(n*n)...(n*n))
Thank you!
0 Kommentare
Akzeptierte Antwort
Matt J
am 2 Nov. 2022
Bearbeitet: Matt J
am 2 Nov. 2022
As I am used to Python I am quite surprised that I can't do it in a simple and obvious way.
cell arrays are a close analogue of Python lists:
L={rand(2), ones(3), eye(4)}
L{1}, L{2},L{3}
Weitere Antworten (2)
Voss
am 2 Nov. 2022
In MATLAB, use a cell array:
C = {magic(4) eye(5) rand(3)}
C{1}
C{2}
C{3}
Or since all your matrices are the same size, use a 3d array:
M = cat(3,magic(4),eye(4),rand(4));
M(:,:,1)
M(:,:,2)
M(:,:,3)
0 Kommentare
Walter Roberson
am 2 Nov. 2022
You would have to construct a custom class for that, and have it define subsref() or use the newer facility to define a method specifically for () access.
You run into semantic problems. If you have defined such a list L already, so that L(2) [for example] returns a numeric matrix, then if you then have
L(2) = magic(7)
then what should happen? You have defined L(2) as returning a numeric matrix, so what is happening in that statement? Is the second entry in the list being replaced? Is L(2) on the left hand side returning the address in memory of the existing second matrix, and what is stored at that location is to be overwritten with the contents of magic(7), including changing any shared references to it?
A = L(2)
L(2) = magic(7)
A is what now? The numeric array that L(2) referred to before? Or did the memory get bashed so that now A also has magic(7) as its contents?
What should
L(2)(3,2)
do? MATLAB will reject that as invalid syntax, but if L(2) is returning a numeric array then does it not make sense that you might want to immediate refer to an element of that numeric array?
I would suggest to you that this is not an avenue worth pursuing. I would suggest to you that you instead use cell arrays such as
L = {A, B, C, D, E}
after which L(2) would be the cell array {B} and L{2} would be the numeric array B . L{2}(3,2) is well defined in MATLAB.
The difference here is that you wanted to be able to use L(2) to get to a complete array, whereas with cell arrays, L(2) is would be a scalar cell array, and L{2} would be what is stored at that scalar. L(2) versus L{2} . If you are willing to live with using L{2} then cell arrays do fine. If you need L(2) to refer to a complete array then you have... challenges.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!