uigetfile function error when one file selected!

조회 수: 2 (최근 30일)
ramez sabra
ramez sabra 2019년 5월 13일
댓글: Walter Roberson 2021년 2월 17일
can someone help me figure this one out?
I want to be able to browse for files and take the selected files in a loop like however i get an error "brace indexing not allowed" however, the code works if i select 2 or more files.
Brace indexing is not supported for variables of this type.
Error in m190507_model_vehicle_test_compare (line 45)
load(files_to_compare{i})
[files_to_compare,path] = uigetfile({'*.mat'},'MultiSelect','on');
for i = 1:1:length(files)
load(files{i})

채택된 답변

Adam Danz
Adam Danz 2019년 5월 13일
편집: Adam Danz 2021년 2월 17일
If you select >1 file, the output of uigetfile() is stored in a cell array which your for-loop is designed to handle. If you select 1 file, the output of uigetfile() is stored as a char array which your for-loop is not designed to handle.
What you want to do is change the char array to a cell array.
if ischar(files_to_compare)
files_to_compare = {files_to_compare};
end
Then enter your for-loop.
I'd add one more conditional to handle the event of selecting 0 files.
if isnumeric(files_to_compare) && isequal(files_to_compare,0)
return % quit the function
% error('User did not select any files.') % _or_ throw an error
end
  댓글 수: 4
laurent jalabert
laurent jalabert 2021년 2월 17일
if isequal(files_to_compare,0) || isequal(path,0)
disp('User pressed cancel')
else
disp(['User selected ', fullfile(path, files_to_compare)])
end
Walter Roberson
Walter Roberson 2021년 2월 17일
if ischar(files_to_compare)
files_to_compare = {files_to_compare};
end
can be replaced by the shorter (but slightly less efficient) code
files_to_compare = cellstr(files_to_compare);

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2019년 5월 13일
This is normal. uigetfile only returns a cell array if more than one file was selected. You can use iscell or ischar to test. And watch out for nothing selected which returns a numeric scalar.
Also you used the wrong variable names between the lines
  댓글 수: 1
ramez sabra
ramez sabra 2019년 5월 13일
yes i just notices. but in my main file the variables are correct. i made some changes here to only extract the relevant code for my case. thanks for pointing it out anyway and thank you for the answer.

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

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by