필터 지우기
필터 지우기

Creating a Combination of Multiple Arrays

조회 수: 7 (최근 30일)
Rachel Anthony
Rachel Anthony 2018년 7월 9일
댓글: Rachel Anthony 2018년 7월 12일
I'm having trouble coming up with code to create a combination between two arrays. In my first array, result, I computed the Cartesian product between the two vectors of A.
>> A = {[1 2 3], [4 5 6]}
c = cell(1,numel(A));
[c{:}] = ndgrid(A{:});
result = cell2mat(cellfun(@(v)v(:), c, 'UniformOutput', false) )
resulta =
1 4
2 4
3 4
1 5
2 5
3 5
1 6
2 6
3 6
My second array is:
resultb =
1 3
2 4
I am trying to create iterations between the rows of result and result b. To make it clearer, I want my output array to look like this:
resultc=
1 4 1 3
2 4 1 3
3 4 1 3
1 5 1 3
2 5 1 3
3 5 1 3
1 6 1 3
2 6 1 3
3 6 1 3
1 4 2 4
2 4 2 4
3 4 2 4
1 5 2 4
2 5 2 4
3 5 2 4
1 6 2 4
2 6 2 4
3 6 2 4
How would I create code to achieve this regardless of the sizes of matrices resulta and resultb? Thanks!

채택된 답변

OCDER
OCDER 2018년 7월 9일
combvec(resulta', resultb')'
  댓글 수: 3
OCDER
OCDER 2018년 7월 12일
I don't know a more direct way off the top of my head, but you could make a combination of indices of the cell arrays instead, and then assemble your combination cell array at the way end. See this example:
resulta = [
1 4
2 4
3 4
1 5
2 5
3 5
1 6
2 6
3 6];
resultb =[
1 3
2 4];
%Just making some example cell arrays
cella = num2cell(resulta);
cella{1} = 'a';
cellb = num2cell(resultb);
cellb{2} = 'b';
%1) create a joined matrix of size (Ma+Mb)x1
cellab = [cella(:); cellb(:)];
%2) find all combination of the linear indices of cella and cellb
IdxA = reshape(1:numel(cella), size(cella));
IdxB = reshape(1:numel(cellb), size(cellb)) + numel(cella); %Add numel(cella) at end because you want the linear index of cellab
ComboIdx = combvec(IdxA', IdxB')';
%3) now make your combination cell array
ComboCell = reshape(cellab(ComboIdx(:)), size(ComboIdx));
Rachel Anthony
Rachel Anthony 2018년 7월 12일
That works, thank you so much!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Matt J
Matt J 2018년 7월 9일
편집: Matt J 2018년 7월 9일
For those without the Neural Network Toolbox,
resultb=[1 3; 2 4];
A = {[1 2 3], [4 5 6],1:size(resultb,2)}
N=numel(A)-1;
[c{1:N+1}]=ndgrid(A{:});
result=[reshape( cat(N+1,c{1:N}) ,[],N ) ,resultb(c{N+1},:)]

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by