How do you create a string from two strings by intersecting them char by char to form a new word using a loop?

str1 = 'Hello'
str2 = 'Canada'
strNew = 'CHaenlaldoa' %This is how the new word should look like.
Thank you in advance!

4 Comments

str1 = 'Hello'
str2 = 'Canada'
m = 1;
for i = [1:numel(str2)]
disp([str2(i) str1(m)])
m = m +1;
end
It's the iteration. it ends at 5, ever the dimension of str1 is 1x4, which is shorter than str2.

Sign in to comment.

 Accepted Answer

Loop not required, just use indexing:
Method one:
>> str1 = 'Hello';
>> str2 = 'Canada';
>> strN = [str1,str2];
>> strN([2:2:end,1:2:end]) = strN
strN = CHaenlaldoa
Method two:
>> strN = str2([1,1],:);
>> strN(1,2:end) = str1;
>> strN = strN(2:end)
strN = CHaenlaldoa

1 Comment

Thanks, Stephen. I may be able to build a loop from yours. Awesome. Its an assignment from school, hence need to be in a loop.

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Products

Release

R2018b

Asked:

on 27 Oct 2018

Edited:

on 27 Oct 2018

Community Treasure Hunt

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

Start Hunting!