user1661303
user1661303

Reputation: 549

Multiplying an array of vectors by each other

I have three time series arrays a, b, c consisting of 1000 values each. They make up a matrix A.

Now, I want to take each array and pointwise multiply it to every other array so that I will get 9 new vectors a^2, ab, ac, ba, b^2, bc, ca, cb, cc.

When I've done this, I want to combine these 9 new arrays into 81 new.

How do I do this? Like I said, I tried building a matrix but it doesnt work the way I wanted it to. I want A to be recognized as a 1*3-matrix contaning 1000*1-arrays. As it is now it just concatenates everything. If A was a 1*3 matrix containing arrays, I could just build the matrix B = transpose(A) * A which would contain all products

I've tried things like

A = [[a] [b] [c]]

A = {a b c}

A = {a; b; c}
defining a, b and c as a = {1, 2, 5, 2 , 1 ...} instead of [1, 2, 5, 2 , 1 ...]

but none of them works.

I don't care if a, b, c, d is stored as lists, column arrays, row arrays or cells, and I'm really not good enough at matlab to know the all the subtile differences, but speed and memory performance is sort of an issue.

Upvotes: 2

Views: 339

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112759

You can do it as follows. Since the functions bsxfun and permute may not be obvious for a Matlab beginner, I suggest you take a look at their doc if needed (see links above).

Given the three data vectors a, b, c, proceed as follows:

A = [ a(:) b(:) c(:) ]; % matrix from column vectors
P = bsxfun(@times,A,permute(A,[1 3 2])); % desired result

The result P is a 1000x3x3 array that contains the desired products. The second and third indices of P are interpreted in the obvious way: 1 corresponds to a, 2 to b and 3 to c. For example, P(10,1,2) is a(10)*b(10); P(50,3,3) is c(50)^2; and so on.

To iterate: simply reshape P into a new A2 matrix and repeat procedure:

A2 = reshape(P,[1000,9,1]);
P2 = bsxfun(@times,A2,permute(A2,[1 3 2])); % result

This gives the result in the 1000x9x9 array P2.

Upvotes: 3

twerdster
twerdster

Reputation: 5027

This problem reduces down to creating index pairs.

%Simulate random data
X=rand(1000,3); 

%Create index multiplication pairs
[i,j] = meshgrid(1:size(X,2),1:size(X,2))

%Multiply together
X = X(:,i(:)).*X(:,j(:));

In this case you will get the following pairs of columns multiplied together

[i(:)';j(:)'] = 
1     1     1     2     2     2     3     3     3
1     2     3     1     2     3     1     2     3

You can repeat the process to remultiply. Be careful though: the matrix size will grow exponentially in the number of iterations.

Upvotes: 3

Related Questions