MATLAB loads file it cannot find

조회 수: 9 (최근 30일)
Fleur
Fleur 2016년 10월 14일
편집: Stephen23 2025년 4월 17일
I want to load a file, and see whether another, related, file exists in the folder. This all happens in a function. The function is called in a script, where the folder where the files are is added to the path. So in this function, I do something like:
if isempty(dir([filename '_extension.mat']))==0
load([filename '_extension.mat']);
else
% code to create such a file
end
To my surprise, the loading works fine, but it does not find the other file in the folder (which does exist). Upon checking, I find that
load(filename);
works fine, but
dir(filename);
gives the error that the file is not found.
How is it possible, that MATLAB can load a file that it cannot find?

채택된 답변

Stephen23
Stephen23 2025년 4월 17일
편집: Stephen23 2025년 4월 17일
"How is it possible, that MATLAB can load a file that it cannot find?"
Because of what you did: "...the folder where the files are is added to the path". As the LOAD documentation explains, LOAD will happily LOAD files from anywhere on the MATLAB Search Path. In contrast DIR only searches the relative or absolute path that it was called with. Which means that your example is easy to replicate:
mkdir ./mysubdir
addpath ./mysubdir
x = pi;
save ./mysubdir/mytestfile.mat x
clearvars
S = load('mytestfile.mat') % loads file from anywhere on the Search Path
S = struct with fields:
x: 3.1416
S = dir('mytestfile.mat') % only looks for folder content in relative/absolute location
S = 0x1 empty struct array with fields: name folder date bytes isdir datenum
So far everything is working exactly as described in the documentation.
In any case, your approach is best avoided: rather than adding folders (containing data files) to the Search Path (which just slows down MATLAB for no benefit) you should use absolute/relative filenames to access those data files.
  댓글 수: 1
Steven Lord
Steven Lord 2025년 4월 17일
FYI for the original poster or someone with a similar question, one tool that can help you build those absolute/relative locations that @Stephen23 mentioned is the fullfile function.
which ode45.m
/MATLAB/toolbox/matlab/funfun/ode45.m
f = fullfile(matlabroot, 'toolbox', 'matlab', 'funfun', 'ode45.m')
f = '/MATLAB/toolbox/matlab/funfun/ode45.m'
exist(f, 'file')
ans = 2

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

KSSV
KSSV 2016년 10월 14일
Use exist to find out whether file exists... doc exist

Image Analyst
Image Analyst 2016년 10월 14일
편집: Image Analyst 2016년 10월 14일
See code in the FAQ to load/process multiple files: http://matlab.wikia.com/wiki/FAQ#How_can_I_process_a_sequence_of_files.3F
When I try your code with a nonexistent filename, it does not step to the load() statement.

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by