Combining Rows of Cell Arrays-- Alternative Way to combvec?
조회 수: 10 (최근 30일)
이전 댓글 표시
I previously had another function that used combvec to combine vectors. I am now using strings in the program and am wondering if there would be a way to do the same thing with cell arrays. For example...
A =
'red' [1]
'blue' [2]
and
B =
[1] [4]
[2] [4]
[3] [4]
[1] [5]
[2] [5]
[3] [5]
[1] [6]
[2] [6]
[3] [6]
I want the combination of cell arrays to happen by row (not sure if that's well explained...) To understand easier, I want the combination, C, to look like this:
C =
[1] [4] 'red' [1]
[2] [4] 'red' [1]
[3] [4] 'red' [1]
[1] [5] 'red' [1]
[2] [5] 'red' [1]
[3] [5] 'red' [1]
[1] [6] 'red' [1]
[2] [6] 'red' [1]
[3] [6] 'red' [1]
[1] [4] 'blue' [2]
[2] [4] 'blue' [2]
[3] [4] 'blue' [2]
[1] [5] 'blue' [2]
[2] [5] 'blue' [2]
[3] [5] 'blue' [2]
[1] [6] 'blue' [2]
[2] [6] 'blue' [2]
[3] [6] 'blue' [2]
How would I do this in a way that would create the combination regardless of the dimensions of the two cell arrays? Thanks in advance!
댓글 수: 0
답변 (1개)
Adam Danz
2018년 7월 12일
편집: Adam Danz
2018년 7월 12일
These two lines below will work for any size 2D arrays.
% Produce an index of A elements to be added to B
idx = transpose(ndgrid(1:size(A,1), 1:size(B,1)));
% Replicate B for each row of A and then add A elements
C = [repmat(B,size(A,1),1), A(idx(:),:)];
C =
{[1]} {[4]} {'red' } {[1]}
{[2]} {[4]} {'red' } {[1]}
{[3]} {[4]} {'red' } {[1]}
{[1]} {[5]} {'red' } {[1]}
{[2]} {[5]} {'red' } {[1]}
{[3]} {[5]} {'red' } {[1]}
{[1]} {[6]} {'red' } {[1]}
{[2]} {[6]} {'red' } {[1]}
{[3]} {[6]} {'red' } {[1]}
{[1]} {[4]} {'blue'} {[2]}
{[2]} {[4]} {'blue'} {[2]}
{[3]} {[4]} {'blue'} {[2]}
{[1]} {[5]} {'blue'} {[2]}
{[2]} {[5]} {'blue'} {[2]}
{[3]} {[5]} {'blue'} {[2]}
{[1]} {[6]} {'blue'} {[2]}
{[2]} {[6]} {'blue'} {[2]}
{[3]} {[6]} {'blue'} {[2]}
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!