Umut C.
Umut C.

Reputation: 51

Combination of Matrices

I have two matrices, one of which (Let's say matrix H) is 4x2 and the other one (matrix N) is 100x2. I want to make a combination for every pair of N, containing every pair of H.

Basically, if my

H = [2 2; 2 4; 4 2; 4 4]
N = [1 1; 1 2; 1 3; ...; 
    10 8; 10 9; 10 10]

I would like to have a final matrix

M = [1 2 2 1; 1 2 4 1; 1 4 2 1; 1 4 4 1; 1 2 2 2; 1 2 4 2; ...; 10 4 4 10] 

of a size 100x4 (because every pair of N will be multiplied |H|=4 times.)

So all the pairs of H matrix will be between all pairs of my N matrix.

I hope I am clear enough.

Upvotes: 1

Views: 87

Answers (2)

ibezito
ibezito

Reputation: 5822

Use the follwing syntax:

%calculates the Cartesian multipication of 1:size(h,1) and 1:size(N,1) 
sets = {1:size(H,1), 1:size(N,1)};
[hInds, nInds] = ndgrid(sets{:});

%generates the output matrix
outRes = [N( nInds(:),1),H( hInds(:),1),H( hInds(:),2),N( nInds(:),2)];

Partial results (displaying just the first rows of the output):

 outRes = 
 1     2     2     1
 1     2     4     1
 1     4     2     1
 1     4     4     1
 1     2     2     2
 1     2     4     2
 1     4     2     2
 1     4     4     2
 1     2     2     3
 1     2     4     3
 1     4     2     3
 1     4     4     3
 ...

Notice that if N is 4x2 and N is 10x2, the final matrix size will be 40x4 and not 100x4 as you mentioned.

Upvotes: 2

Sardar Usama
Sardar Usama

Reputation: 19689

Try this:

H= [2 2; 2 4; 4 2; 4 4];
N= fix(100*(rand(10,2))) % Replace this with your N matrix

iter=0;
for i=1:10
for j=1:4
    iter=iter+1;
A(iter,:)=[N(i,1), H(j,1:2), N(i,2)];
end
end

A

Upvotes: 1

Related Questions