How do I get a mixed string from several arrays of strings?

1 view (last 30 days)
I have several arrays of strings which is used to store collections of factors. for example:
factor1={'male';'female'}; factor2={'easy'; 'normal';'hard'};
I want to create a set of filenames for following works.
This is what I want to get:
filename =
'male_easy.txt'
'male_normal.txt'
'male_hard.txt'
'female_easy.txt'
'female_normal.txt'
'female_hard.txt'
This is what I tried:
filename={};
for i=1:length(factor1)
for j=1:length(factor2)
filename=[filename,[factor1(i),'_',factor2(j),'.txt']];
end
end
I noticed that [factor1(i),'_',factor2(j),'.txt'] will became↓(when i=1,j=1)
filename =
'male' '_' 'easy' '.txt'
I failed in getting the strings together.
How can I fix it?

Accepted Answer

Orion
Orion on 29 Oct 2014
Hi,
that's because you used "()" instead of "{}" to access element of a cell, and a "," instead of ";" to concatenate vertically.
you juste need to do :
factor1={'male';'female'};
factor2={'easy'; 'normal';'hard'};
filename={};
for i=1:length(factor1)
for j=1:length(factor2)
filename=[filename;[factor1{i},'_',factor2{j},'.txt']];
end
end

More Answers (1)

Mischa Kim
Mischa Kim on 29 Oct 2014
Edited: Mischa Kim on 29 Oct 2014
Pelle, use instead
for ii = 1:numel(factor1)
for jj = 1:numel(factor2)
filename{jj+(ii-1)*numel(factor2)} = strcat(factor1(ii),'_',factor2(jj),'.txt');
end
end
Note that i and j are also used as the imaginary unit.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!