Effacer les filtres
Effacer les filtres

concatenate each element of two arrays

12 vues (au cours des 30 derniers jours)
Mohit
Mohit le 1 Fév 2014
Commenté : Azzi Abdelmalek le 3 Fév 2014
I have two arrays, can you please help me how can I concatenate each element of both arrays.
e.g. A=['a' 'b' 'c'] B = ['1' '2']
I want ['a1' 'a2' 'b1' 'b2' 'c1' 'c2']
Thanks
  1 commentaire
Shivaputra Narke
Shivaputra Narke le 1 Fév 2014
you can do it using for loop

Connectez-vous pour commenter.

Réponse acceptée

Azzi Abdelmalek
Azzi Abdelmalek le 1 Fév 2014
Modifié(e) : Azzi Abdelmalek le 1 Fév 2014
A=['a' 'b' 'c'];
B = ['1' '2'];
[ii,jj]=ndgrid(1:numel(A),1:numel(B));
out=arrayfun(@(x,y) [A(y) B(x)],jj(:),ii(:),'un',0);
out=sort(out)
  3 commentaires
Mohit
Mohit le 3 Fév 2014
Thanks Azzi!
Jos (10584)
Jos (10584) le 3 Fév 2014
No need for arrayfun to concatenate, or using sort when you re-arrange the inputs and outputs to/from ndgrid:
[bb,aa] = ndgrid(B,A) ;
C = [aa(:) bb(:)]

Connectez-vous pour commenter.

Plus de réponses (3)

Jan
Jan le 1 Fév 2014
A = {'a' 'b' 'c'};
B = {'1' '2'};
C = strcat(repmat(A, 2, 1), repmat(B', 1, 3))
Notice that A and B are cell strings, not char vectors.
  1 commentaire
Azzi Abdelmalek
Azzi Abdelmalek le 3 Fév 2014
Mohit, this also gives you what you want, just add
C(:)'

Connectez-vous pour commenter.


Jos (10584)
Jos (10584) le 3 Fév 2014
A=['a' 'b' 'c']
B = ['1' '2']
C = allcomb(A,B)

Wayne King
Wayne King le 1 Fév 2014
Make A and B cell arrays of strings, but B has to be the same length as A so you'll have to repeat the 2
A = {'a','b','c'};
B = {'1','2','2'};
strcat(A,B)
  1 commentaire
Mohit
Mohit le 3 Fév 2014
Thanks, it will give me 3 elements in result matrix while I wanted 6.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Operators and Elementary Operations 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