slowhead
slowhead

Reputation: 5

Matrix with each element representing a vector

In Matlab, I want to have a matrix in which every element is a vector, so that I can identify the stored vector e.g., x(1,2) = vec5 or x(3,2) = vec1 etc. Let's say:

x=[ vec1 vec2 vec3; vec4 vec5 vec6; vec2 vec1 vec9]; 

I was thinking on the lines of "Matrix of cells" or even 3-d matrices. Running out of ideas! :s I would appreciate your help

Upvotes: 0

Views: 334

Answers (1)

Mehrwolf
Mehrwolf

Reputation: 8527

If really every element should be a vector, a cell is the most flexible solution as you can have vectors with different length in them.

vec1 = 1:2;
vec2 = 1:3;
vec3 = 1:4;
x{1,1} = vec1;
x{2,1} = vec2;
x{2,2} = vec3;
x
x = 
    [1x2 double]              []
    [1x3 double]    [1x4 double]

And you access the vectors using x(1,1), x(2,1)etc. Unused elements contain an emtpy vector.

If all vectors are of the same length, store them in a matrix or in a 3D array, e.g.

vec1 = rand(1, 3);
vec2 = rand(1, 3);
vec3 = rand(1, 3);
%# Matrix with one vector per column.
x = [vec1.', vec2.', vec3.'];
x =
    0.9649    0.9572    0.1419
    0.1576    0.4854    0.4218
    0.9706    0.8003    0.9157

%# 3D array
y = nan(2, 2, length(vec1));
y(1,1,:) = vec1;
y(1,2,:) = vec2;
y(2,2,:) = vec3;
y
y(:,:,1) =
    0.9649    0.9572
       NaN    0.1419

y(:,:,2) =
    0.1576    0.4854
       NaN    0.4218

y(:,:,3) =
    0.9706    0.8003
       NaN    0.9157

In the 3D-case, unused elements are initialized to NaN. If you would like them to be zero, use y = zeros(2, 2, length(vec1)); instead.

Upvotes: 3

Related Questions