MATLAB: How to get a script to return a 0 instead of stopping the loop if a specified field does not exist

field does not existfor loop

mat = dir('*.mat');
a = zeros(length(mat),1);
for q = 1:length(mat) load(mat(q).name); a(q,1) = (DATA.Rating); end
Heres a basic script I'm using to loop through a set of matlab files and assign the number stored in DATA.Rating to my matrix a. However, some of the files do not have the DATA.Rating field, so the loop stops when it reaches it. Is it possible for me to have the loop assign 0 whenever DATA.Rating does not exist so that it can continue?

Best Answer

nmat = length(mat);
a = zeros(nmat, 1);
for q = 1:nmat
matdata = load(mat(q).name);
if isfield(matdata,'DATA') && isfield(matdata.DATA, 'Rating')
a(q,1) = matdata.DATA.Rating;
end
end
Related Question