Reputation: 227
I'm making a program which need a reference folder with .txt
files inside. Those files are read automatically. In the next step, the user is asked to choose a file and the program will read the specified file.
The thing is, I want the reference to be in a different folder (which will stay the same). If my current folder is the one containing the user's data, how can I read my reference files?
Here's the codeline for the automatic file opening part, as it is right now :
fichierref = 'H:\MATLAB\Archive_08112012';
files = dir(fullfile(fichierref, '*.txt'));
numberOfFiles = numel(files);
for d = 1:numberOfFiles
filenames(d) = cellstr(files(d).name);
end
It does open the files automatically, but only if my current folder is the Archive_08112012.
EDIT:
I'll add this. This is how I open the files.
headerlinesIn = 11;
delimiterIn=' ';
if numberOfFiles > 1
for i=1:numberOfFiles
data = importdata(filenames{i},delimiterIn,headerlinesIn);
It has exactly the same line if numberOfFiles = 1, but there is no for loop.
Upvotes: 1
Views: 21485
Reputation: 11168
Debug your code and you'll quickly see what's going wrong:
files = dir(fullfile(fichierref, '*.txt'));
..
filenames(d) = cellstr(files(d).name);
you're building a cell array of the filenames (note: names, not the full path). If you had inspected the contennt of this array, you'd have seen what's going wrong with the file loading:
data = importdata(filenames{i},delimiterIn,headerlinesIn);
you issue impordata
on the filename; when you don't specify the full path, matlab goes looking for the file in the current directory (or other directories added to the matlab path, not important right here).
It must be clear by now you'll want to switch to using importdata with the full path of the file you're after. Do this with fullfile:
other_directory = 'c:\whatever\it\might\be'
data = importdata(fullfile(other_directory,filename{i}),delimiterIn,headerlinesIn);
Upvotes: 3
Reputation: 10708
To refer to a file outside your current working directory, you need the full path (or relative path) to the file. You can build paths using fullfile
, as you did in your example code. Use the full (or relative) path instead of just filenames when calling your importdata
function.
Upvotes: 2
Reputation: 2750
You should keep using fullfile
. I just post an example taken from http://www.mathworks.com/help/matlab/ref/fullfile.html
f = fullfile('myfolder','mysubfolder','myfile.m')
f =
myfolder\mysubfolder\myfile.m
Upvotes: 1