concatenate each element of two arrays

17 次查看(过去 30 天)
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

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2014-2-1
编辑:Azzi Abdelmalek 2014-2-1
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 个评论
Jos (10584)
Jos (10584) 2014-2-3
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(:)]

请先登录,再进行评论。

更多回答(3 个)

Jan
Jan 2014-2-1
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.

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

Wayne King
Wayne King 2014-2-1
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)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by