Effacer les filtres
Effacer les filtres

Combining Rows of Cell Arrays-- Alternative Way to combvec?

10 vues (au cours des 30 derniers jours)
Rachel Anthony
Rachel Anthony le 12 Juil 2018
Modifié(e) : Adam Danz le 12 Juil 2018
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!

Réponses (1)

Adam Danz
Adam Danz le 12 Juil 2018
Modifié(e) : Adam Danz le 12 Juil 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]}

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by