split up file name into strings...

23 vues (au cours des 30 derniers jours)
Chris E.
Chris E. le 18 Nov 2012
Well I have a file name that I need to split up into 2 main parts and then put them into matlab as numbers.
The average name of the file is:
curr_1.564_image_002.tiff
I need:
curr = 1.564
image = 2
Here is what I have right now, this is really ugly way of doing this...
[~,o,p] = fileparts(fig_dir(1).name);
[k y] = strtok(o,'_');
y = y(2:end);
[curr z] = strtok(y,'_');
image = z(8:end);
If I can split up this file name into these two parts that is all I need. I was unsure how to do this in MATLAB. Thank you, Chris

Réponse acceptée

Jan
Jan le 19 Nov 2012
Modifié(e) : Jan le 19 Nov 2012
And another approach:
name = 'curr_1.564_image_002.tiff';
numbers = sscanf(name, 'curr_%g_image_%d');

Plus de réponses (2)

Image Analyst
Image Analyst le 18 Nov 2012
Modifié(e) : Image Analyst le 18 Nov 2012
In the absence of anything to suggest the need for anything more general, this code will work for that filename and any others that are the same format and length:
filename = 'curr_1.564_image_002.tiff'
curr = filename(6:10)
imageNumber = filename(18:20)
If things can vary position, then you must say so. Otherwise this will work fine and is the simplest you can get.
% Alternate, more general way
underlineLocations = find(filename == '_')
curr2 = filename(underlineLocations(1)+1:underlineLocations(2)-1)
[folder, baseFileName, extension] = fileparts(filename);
imageNumber2 = baseFileName(18:end)
In your edited/expanded question you're getting them as strings, but just in case you want them as numbers....
% If you want them as numbers instead of strings, use the str2double function
dblCurr2 = str2double(curr2)
intImageNumber2 = int32(str2double(imageNumber2))
By the way, don't use image as a variable name because that's the name of a built-in function.

Azzi Abdelmalek
Azzi Abdelmalek le 18 Nov 2012
Modifié(e) : Azzi Abdelmalek le 18 Nov 2012
s='curr_1.564_image_002.tiff'
idx=regexp(s,'_')
ii=regexp(s,'.tiff')
curr=str2num(s(idx(1)+1:idx(2)-1))
image=str2num(s(idx(3)+1:ii-1))

Community Treasure Hunt

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

Start Hunting!

Translated by