Combine 2 char vectors

19 views (last 30 days)
Nicolas Baduel
Nicolas Baduel on 28 May 2018
Answered: Stephen23 on 29 May 2018
Hi everyone, Here are two vectors :
A='IMDOINGATEST'
B='ABCDE'
I would like to get this : (a regular mix)
C='IAMBDCODIENAGBACTDEESATB'
Note that A can be smaller than B but A won't repeat in B. Only B repeats in A.
Thank you !

Accepted Answer

Ameer Hamza
Ameer Hamza on 28 May 2018
This will mix them as described in question
C = repmat(' ', 1, 2*numel(A))
C(1:2:end) = A;
C(2:2:end) = [repmat(B, 1, floor(numel(A)/numel(B))) B(1:rem(numel(A), numel(B)))];
For example,
A='IMDOINGATEST'
B='ABCDE'
will produce
C =
'IAMBDCODIENAGBACTDEESATB'
and
A='IMDO'
B='ABCDE'
will mix to form
C =
'IAMBDCOD' % no repetition of A
  2 Comments
Nicolas Baduel
Nicolas Baduel on 28 May 2018
I will try this tomorrow, thank you for the answer !
Ameer Hamza
Ameer Hamza on 29 May 2018
You are welcome.

Sign in to comment.

More Answers (1)

Stephen23
Stephen23 on 29 May 2018
A slightly different approach:
>> A = 'IMDOINGATEST';
>> B = 'ABCDE';
>> C = repmat(B,1,ceil(numel(A)/numel(B)));
>> C = reshape([A;C(1:numel(A))],1,[])
C = IAMBDCODIENAGBACTDEESATB
Or
>> A = 'IMDO';
>> B = 'ABCDE';
>> C = repmat(B,1,ceil(numel(A)/numel(B)));
>> C = reshape([A;C(1:numel(A))],1,[])
C = IAMBDCOD

Categories

Find more on Characters and Strings 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!