concatenate each element of two arrays
24 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Mohit
am 1 Feb. 2014
Kommentiert: Azzi Abdelmalek
am 3 Feb. 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 Kommentar
Akzeptierte Antwort
Azzi Abdelmalek
am 1 Feb. 2014
Bearbeitet: Azzi Abdelmalek
am 1 Feb. 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 Kommentare
Jos (10584)
am 3 Feb. 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(:)]
Weitere Antworten (3)
Jan
am 1 Feb. 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 Kommentar
Azzi Abdelmalek
am 3 Feb. 2014
Mohit, this also gives you what you want, just add
C(:)'
Wayne King
am 1 Feb. 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)
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!