How do you populate a struct with multiple loaded .mat files?

조회 수: 22 (최근 30일)
David Mabwa
David Mabwa 2020년 9월 29일
편집: David Mabwa 2020년 10월 14일
Hi,
So I have this code below that loads my data. It works fine when not wrapped in a function, however when I wrap it in a function it doesn't work. While debugging, I can see it loading my files, however, when I get to the end of the function, they don't load onto the current workspace.
Secondly, when I assign a variable for the data files to load into, they load fine when I am only dealing with one file. When I try to load multiple files however, it doesn't run as expected. It keeps overwriting each loaded array in the struct.
I'm not at all sure what i'm doing wrong
Any help is appreciated.
Thank you!
function S=LoadData % When not wrapped in function, doesn't output S
[file,path]=uigetfile(...
{'*.m;*.mlx;*.fig;*.mat;*.slx;*.mdl',...
'MATLAB Files (*.m,*.mlx,*.fig,*.mat,*.slx,*.mdl)';
'*.jpg;*.jpeg;*.png;*.tif;*.tiff',...
'Images (*.jpg,*.jpeg,*.png,*.tif,*.tiff)'},...
'Select a File','MultiSelect','on');
if isequal(file,0)
clear file
clear path
else
if iscell(file)
for k=1:size(file,2)
S=load(fullfile(path,file{k})); % Keeps overwriting S rather than appending
end
else
S=load(fullfile(path,file));
end
clear file
clear path
end
end

채택된 답변

Xingwang Yong
Xingwang Yong 2020년 9월 30일
There is a contradiction between your statement and your comment in code. I assume you are asking about " however when I wrap it in a function it doesn't work".
In your case, the scope of variable 'S' is limited within the function LoadData(). You can use nested function to change this behaviour.
function yourMainScript
S = [];
S = LoadData(); % now S will be in the workspace of the main script
function S=LoadData
% ...
end
end
As for overwriting, you can avoid it like this
if isempty(S)
S = load(fullfile(path,file{k}));
else
tmp = load(fullfile(path,file{k}));
for fn = fieldnames(tmp)'
S.(fn{1}) = tmp.(fn{1}); % this will overwrtie if have same fieldnames
end
end
Loop over fields of a struct can be found here:
  댓글 수: 1
David Mabwa
David Mabwa 2020년 10월 14일
편집: David Mabwa 2020년 10월 14일
Thank you, that worked like a charm. My main issue was with the overwriting.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by