matrix of matrices - matrix with matrices inside it
Show older comments
How would I create a matrix of matrices, such that A = [[1 2 3 4] [5 6 7 8]]?
I mean a matrix with matrices inside of it.
Answers (2)
JESUS DAVID ARIZA ROYETH
on 11 Dec 2019
Edited: JESUS DAVID ARIZA ROYETH
on 11 Dec 2019
use cell array:
A = {[1 2 3 4] [5 6 7 8]}
A{1}% get matrix 1
A{2}% get matrix 2
7 Comments
Mandar Kadwekar
on 4 Jun 2022
How would I get the 2nd element of 1 st matrix?
A = {[1 2 3 4] [5 6 7 8]};
A{1}(2)
Mandar Kadwekar
on 5 Jun 2022
I was writingA{1(2)}. Thanks. Also how can I extract 2 nd element of both matix to get displayed in another row or column matrix?
A = {[1 2 3 4] [5 6 7 8]};
cellfun(@(x)x(2),A)
Mandar Kadwekar
on 5 Jun 2022
Can you explain how this function works as I have to apply it on another matrix I am working on.
Does this help:
% Define sample data:
A = {[1 2 3 4] [5 6 7 8]} % A 1 by 2 cell array with each cell containing a matrix that is a 1-by-4 row vector.
% Define an anonymous function:
functionHandle = @(inputArg) inputArg(2) % Return second element of whatever inputArg is passed in.
% Apply the function to each cell of A.
% This will take each cell of A and take the matrix out, and then pass it to functionHandle
% which will take the second element of that matrix and return it.
results = cellfun(functionHandle, A)
Mandar Kadwekar
on 5 Jun 2022
Yes this exactly did what I intended to do with the matrix. Thanks.
Image Analyst
on 11 Dec 2019
Some more ways
A = [1 2 3 4; 5 6 7 8] % Create a 2-D array with the vectors in it.
A = cat(2, [1 2 3 4], [5 6 7 8]); % Create a 2-D array with the vectors in it.
For more on cell arrays, like in Jesus's answer, see The FAQ. One advantage of cell arrays is that each cell can contain anything : matrices of all the same or all different sizes, string, tables, even other cell arrays. Any MATLAB variable can be put into the cell and each cell can be totally different.
Another variable that can contain matrices is a table, though I think each column in a table must contain the same size array.
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!