3

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!

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Jamie, it's polite to upvote good answers and eventually "accept" the one you feel is best once you feel the question has been answered (and the option becomes available).
3

Here's a more concise version using sprintf and strsplit:

files = strsplit(sprintf('chr%i.fa ',1:22),' ');

files{end} = 'chrX.fa';

Comments

2

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']

Comments

1

Try:

files = [strtrim(cellstr(num2str((1:22)','chr%d.fa'))) ; 'chrX.fa']

Comments

0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.