Variable in a string name

7 visualizaciones (últimos 30 días)
Andrew
Andrew el 23 de Sept. de 2014
Comentada: Andrew el 23 de Sept. de 2014
I am reading columns of binary files to plot. I have all my files in one folder and I want to plot them and pull out certain data. How can I set up a loop that will go through all the files?
My idea so far:
1) Use D= dir('W:\Folder')
to retrieve the names of all the files
2) for i= 1:70
str = ('W:\Folder\D(i)\Data')
fid = fopen(str);
How can I insert the different names in the array D from step 1?
I tried sprintf but I believe there is a problem because it's a path.
Thank you for your help

Respuesta aceptada

Geoff Hayes
Geoff Hayes el 23 de Sept. de 2014
Andrew - try using fullfile instead
foldername = 'W:\folder';
files = dir(foldername);
for k=1:length(files)
% ignore directories
if ~files(k).isdir
% build the file name
filename = fullfile(foldername,files(k).name);
% open the file
fid = fopen(filename);
if fid>0
% do stuff with file contents
% close the file
fclose(fid);
end
end
end
You can use sprintf as well (something like str = sprintf('W:\folder\%s\,files(k).name)' but the above should work just as well.
  2 comentarios
Image Analyst
Image Analyst el 23 de Sept. de 2014
Very robust. But after looking at his question again, I think he want to use dir() to get directories rather than files . Why do I think that? Because D(i) is in the middle of "W:\Folder\D(i)\Data" so he intends D(i) to be a folder name. So I think he wants all the subfolders of "Folder" and Data are files inside the subfolders, and unfortunately Data may not have any extension to the filename. SO maybe "if ~files(k).isdir" should actually be "if files(k).isdir"
Andrew
Andrew el 23 de Sept. de 2014
Thank you, I was able to work it out using fullfile

Iniciar sesión para comentar.

Más respuestas (1)

Image Analyst
Image Analyst el 23 de Sept. de 2014
Use sprintf() to construct the filename from i.
filename = sprintf('W:/Folder/%s/Data.dat', D(i).name);

Categorías

Más información sobre File Operations en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by