load file with try/catch error

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

回答 (1 件)

Bjorn Gustavsson
Bjorn Gustavsson 2020 年 5 月 2 日

1 投票

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 件のコメント

Harshil Patel
Harshil Patel 2020 年 5 月 2 日
No still i shows error.
now code is
filename = input('Enter file name:')
try
load('-mat','filename')
catch
disp(['Could not find file: ',filename]);
end
and i have one file named 'a.mat' which i want to load but when i enter name it shows error message as shown below
Enter file name:a.mat
??? Undefined variable "a" or class "a.mat".
Error in ==> loadfile at 2
filename = input('Enter file name:')
Bjorn Gustavsson
Bjorn Gustavsson 2020 年 5 月 3 日
Read the help for input! See especially at the second paragraph:
STR = input(PROMPT,'s') returns the entered text as a MATLAB string,
without evaluating expressions.
HTH
Walter Roberson
Walter Roberson 2020 年 5 月 3 日
And use
load(filename)
if filename is a variable containing the name of the file.
Bogdan -Ervin
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.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeScope Variables and Generate Names についてさらに検索

質問済み:

2020 年 5 月 2 日

コメント済み:

2024 年 4 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by