load file with try/catch error
조회 수: 15 (최근 30일)
이전 댓글 표시
how to write code that propmts user for name of file to load and then load data from file with try/catch function and display error if specific file not displayed.
i tried this code but it sows error...
clear all;
filename = input('Enter file name:')
load -mat filename
try
load('fileName')
catch
'File did not find';
end
댓글 수: 0
답변 (1개)
Bjorn Gustavsson
2020년 5월 2일
With your first call of load:
load -mat filename
matlab will try to load a file with the explicit filename filename (or filename.mat). regardless of what the variable filename is. load on that line is run as the command load, the additional text on that line is taken as litteral strings. This is very convenient when running stuff from the command-line (and for scripts with fixed inputs), but confusing when converting to general-purpose functionality.
If you remove that line your code should work. You could consider changing:
load('fileName')
to:
load('-mat','fileName')
and
'File did not find';
to
disp(['Could not find file: ',filename]);
Also when asking about help with error-hunting, you get better replies if you include the full error-message.
(and cut the clear all, it's uggly)
HTH
댓글 수: 4
Walter Roberson
2020년 5월 3일
And use
load(filename)
if filename is a variable containing the name of the file.
Bogdan -Ervin
2024년 4월 24일
What type of error is file not found? Because I want to write a try with 2 catch, where the first catch is for file not found, and other one contains a nested try catch.
참고 항목
카테고리
Help Center 및 File Exchange에서 Scope Variables and Generate Names에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!