Reputation: 680
I have a list of files that I would like analyze. They are all named chr1.fa, chr2.fa, ... , chr22.fa, chrX.fa
I would like to store all of these filenames in an array. I know in python you can do
files = ["chr"+str(x)+".fa" for x in range(1,22)]+["chrX.fa"]
I have been having an embarrassingly difficult time trying to do the equivalent in Matlab. Otherwise, I'll have to initialize the file like:
files = {'chr1.fa','chr2.fa',...,'chr22.fa','chrX.fa'}
Which is really not ideal since I may be processing more files.
Any pointers on where I should be looking would be greatly appreciated.
Thanks!
Upvotes: 3
Views: 1903
Reputation: 706
Old topic, but starting in 16b, using the new string datatype makes this pretty easy:
>> files = ["chr" + (1:22) + ".fa", "chrX.fa"]'
files =
23×1 string array
"chr1.fa"
"chr2.fa"
"chr3.fa"
"chr4.fa"
"chr5.fa"
"chr6.fa"
"chr7.fa"
"chr8.fa"
"chr9.fa"
"chr10.fa"
"chr11.fa"
"chr12.fa"
"chr13.fa"
"chr14.fa"
"chr15.fa"
"chr16.fa"
"chr17.fa"
"chr18.fa"
"chr19.fa"
"chr20.fa"
"chr21.fa"
"chr22.fa"
"chrX.fa"
Upvotes: 0
Reputation: 124563
Try:
files = [strtrim(cellstr(num2str((1:22)','chr%d.fa'))) ; 'chrX.fa']
Upvotes: 1
Reputation: 74940
Here's a more concise version using sprintf
and strsplit
:
files = strsplit(sprintf('chr%i.fa ',1:22),' ');
files{end} = 'chrX.fa';
Upvotes: 3
Reputation: 12693
Here's a one-liner, just for fun. @Phonon's way works too obviously.
files = [arrayfun(@(x)strcat('chr',num2str(x),'.fa'),(1:22)','uni',0); 'chrX.fa']
Upvotes: 2
Reputation: 12737
This isn't exactly as compact as Python, but it'll do the job for you.
N = 20;
prefix = 'chr';
suffix = '.fa';
names = cell(N,1);
for n = 1:N
names{n} = [prefix int2str(n) suffix];
end
names{N+1} = [prefix 'X' suffix];
You can fetch names by names{index}
. Note the curly braces, since this is a cell array, not a multidimensional character array.
Upvotes: 3