MATLAB Answers

Extracting values from file names to array

1 view (last 30 days)
g
g on 22 Oct 2019
Edited: Stephen Cobeldick on 22 Oct 2019
Let's say I have a directory "mydirectory" and in it, I have some files
file_234.txt
file_356.txt
file_567.txt
file_987.txt
and I want to form an array in Matlab out of the respective numbers.
234
356
567
987
How can I go into the directory, extract the information from the files, and put each value into the array?
Thanks!

  0 Comments

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 22 Oct 2019
Edited: Stephen Cobeldick on 22 Oct 2019
>> D = 'path to the folder where the files are saved';
>> S = dir(fullfile(D,'file_*.txt'));
Method one: regexp:
>> V = str2double(regexp({S.name},'\d+','match','once'))
V =
234 356 567 987
Method two: sscanf:
>> V = sscanf([S.name],'file_%d.txt') % change to suit your filenames
V =
234
356
567
987

  0 Comments

Sign in to comment.

More Answers (1)

Sean de Wolski
Sean de Wolski on 22 Oct 2019
fn = ["file_234.txt"
"file_356.txt"
"file_567.txt"
"file_987.txt"]
double(extractBetween(fn, "_", "."))

  0 Comments

Sign in to comment.

Sign in to answer this question.

Tags


Translated by