矩阵的组合

Combination of Matrices

我有两个矩阵,其中一个(假设矩阵 H)是 4x2,另一个(矩阵 N)是 100x2。 我想对每一对N做一个组合,包含每一对H。

基本上,如果我的

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

我想要一个最终矩阵

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] 

大小为 100x4(因为每对 N 将乘以 |H|=4 次。)

所以 H 矩阵的所有对都将在我的 N 矩阵的所有对之间。

希望我说得够清楚了。

使用以下语法:

%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)];

部分结果(仅显示输出的第一行):

 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
 ...

请注意,如果 N 为 4x2 且 N 为 10x2,则最终矩阵大小将为 40x4 而不是您提到的 100x4。

试试这个:

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