Filename value extraction: code simplification

1 view (last 30 days)
Being new to Matlab, it took me half a day to get my code to work at all, but now I'm wondering if it's possible to get it to work faster, in a better style and with less "detour" due to format-changing and such. It's a follow-up to a question I asked on Stack Overflow, but I find it to be more fitting to a forum like this here than S-O. Please tell me if you think it's better to stick to one platform ;)
What I want to do: I got files named abc123.xml, abc124.xml, abc133.xml etc. Now I just need the numerical value as a :,1 numerical array to be able to interactively select and process the data. This is what I got so far:
xml_filelist = dir('subfolder/*.xml'); % giving a :,1 struct with 5 fields where the first is the filename
xml_filelist = struct2table(xml_filelist); % converting it to a :,5 table where the first is the filename
xml_filelist = table2cell(xml_filelist(:,1)); % converting the first column to a cell array to be able to regexp it
xml_num = regexp(xml_filelist, '(\d+)', 'once', 'tokens'); % extracting the numerical value
xml_num = cellfun(@(x)str2double(x), xml_num); % converting it from string cell array to double values
This leaves me with an array like [123; 124; 133], which is what I need. Now is there any way to simplify the code above?

Accepted Answer

Walter Roberson
Walter Roberson on 1 Dec 2017
xml_filelist = dir('subfolder/*.xml');
xml_filenames = {xlm.filelist.name};
xml_num = str2double( regexp(xml_filenames, '\d+', 'match', 'once') );
  4 Comments
Andreas B
Andreas B on 2 Dec 2017
I feel very stupid for that one, sorry. Will be the first thing I try on monday, as I it's a company license.

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!