justik
justik

Reputation: 4255

Matlab, matrix of arrays

There are 3 matrices A,B,C:

A=[0 1;2 3]
B=[4 5;6 7]
C=[8 9;10 11]

How to create a new matrix D(2,2) so as its elements are arrays of a type

D = [{A(1,1), B(1,1), C(1,1)} {{A(1,2), B(1,2), C(1,12}; 
     {A(2,1), B(2,1), C(2,1)} {A(2,2), B(2,2), C(2,2)}]

For example: Using an operator D(1,1) gives the result

0, 4, 8

The bracket {} are only illustrative and do not represent a matlab syntax...

Upvotes: 2

Views: 1794

Answers (2)

Amro
Amro

Reputation: 124553

You could stack the matrices along the third dimension:

D = cat(3,A,B,C);

Then you could access as:

>> D(1,1,:)
ans(:,:,1) =
     0
ans(:,:,2) =
     4
ans(:,:,3) =
     8

if you want to get a 1D-vector:

>> squeeze(D(1,1,:))     %# or: permute(D(1,1,:),[1 3 2])
ans =
     0
     4
     8

If you prefer to use cell arrays, here is an easier way to build it:

D = cellfun(@squeeze, num2cell(cat(3,A,B,C),3), 'UniformOutput',false);

which can be accessed as:

>> D{1,1}
ans =
     0
     4
     8

Upvotes: 3

PetPaulsen
PetPaulsen

Reputation: 3508

You are almost there:

D = [{[A(1,1), B(1,1), C(1,1)]} {[A(1,2), B(1,2), C(1,2)]};
     {[A(2,1), B(2,1), C(2,1)]} {[A(2,2), B(2,2), C(2,2)]}]

(you see the additional branches?)

D is now a cell array, with each cell containing a 1x3 matrix.

To access the cell array use this syntax:

D{1,1}

Upvotes: 1

Related Questions