extract number out of the file title for further usage
Mostra commenti meno recenti
hi everyone,
i have many files inside a folder. The files have names like 12E.dat, 13.dat, ...100.dat i use the following code to load them
files = dir('*.dat');
for k = 1:numel(files)
D = load(files(k).name);
tof = D(:,2)*1000;
...
end
I want to creat an array like E = [12, 13, ..., 100] taken out of the title of the file. Is their a way to realize this?
thanks a lot in advance
Risposta accettata
Più risposte (2)
Image Analyst
il 28 Nov 2013
0 voti
Did you try sscanf()?
eFKa
il 28 Nov 2013
0 voti
4 Commenti
Image Analyst
il 28 Nov 2013
Modificato: Image Analyst
il 28 Nov 2013
OK, just be aware that if your filenames are "12E.dat, 13.dat, ...100.dat" like you said, you'll get a nan for the 12E file (or any other file that is not strictly pure numbers", so that's why I recommended sscanf() which is more robust, see:
% Jos code:
values = str2double(filename)
% Image Analyst code:
theValue = sscanf(filename, '%d', 1)
In the command window:
values =
NaN
theValue =
12
Notice my code gives the desired 12 for the "12E" filename whereas str2double() gives a nan. So if you want to skip filenames with non-numerical characters in them, you'll have to use isnan() to check for that, or else use my code to pull out just the number. But that code only handles filenames if they start with a number. It could be made even more robust by getting rid of non-numbers wherever they appear. So look at this more robust code:
filename = 'xyz12E.dat'; % Number in the middle
% Jos code:
values = str2double(filename)
% Image Analyst code:
numbersIndexes = (filename >= '0' & filename <= '9')
filename(~numbersIndexes) = ' '
theValue = sscanf(filename, '%d', 1)
values =
NaN
numbersIndexes =
0 0 0 1 1 0 0 0 0 0
filename =
12
theValue =
12
I've just learned to always write super robust code because if I don't, and I roll out my code worldwide and one of my users does something unexpected, they'll blame the software, not themselves, and my software (and me!) will get a reputation as "buggy" or unreliable, and I can't afford that.
Jos (10584)
il 28 Nov 2013
I second that, ImageAnalyst. Note that two distinct files, like 12E.dat and 12F.dat, end up having the same label …
Image Analyst
il 28 Nov 2013
Very good point (that I overlooked). Sometimes things like that will slip by and you'll only realize it when you get an angry email from a user about how your code does not work. Like they say in software development "It's hard to make code idiotproof because idiots are so ingenious." But perhaps the 12E was just a typo - who knows? But my first assumption is that the user meant what he said.
Categorie
Scopri di più su Environment and Settings in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!