Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab string arrays

Tags:

string

matlab

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!

like image 838
mortonjt Avatar asked Sep 18 '26 22:09

mortonjt


2 Answers

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.

like image 169
Phonon Avatar answered Sep 21 '26 11:09

Phonon


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

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

files{end} = 'chrX.fa';
like image 28
Jonas Avatar answered Sep 21 '26 11:09

Jonas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!