Combining Rows of Cell Arrays-- Alternative Way to combvec?
10 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Adam Danz
on 12 Jul 2018
Edited: Adam Danz
on 12 Jul 2018
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 Comments
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!