MATLAB: How to ignore non-existing variables in a for loop

for loop

Hi,
I am trying to load different structures with a for loop. However, some of the structures will not contain the field that is used in the for loop.
I think I need the 'if', 'continue', 'end' statement, but I'm struggling with how to define the 'if'.
MOVEMENT = {'RF1','RF2','RF3','RGV1','RGV2','RGV3','RS1','RS2','RS3'};
'MOVEMENT' contains the tasks I want to select, but some of the structures I load have e.g. RGV1 and RGV3 but not RGV2.
I tried:
if exist(MOVEMENT{f}, 'var') == 0
end
continue
But this does not seem to work.
Code looks like this currently:
for f = 1:length(MOVEMENT)
% File does not exist
% Skip to bottom of loop and continue with the loop
if exist(MOVEMENT{f}, 'var') == 0
H18.(MOVEMENT{f}) = load(['D:\Toolkit\Backup\CRD-L-06022\c\Users\u0102306\Box Sync\DATA\PROCESSED_DATA\IDCA\IMU\H18\Mean_Subject_' ...
MOVEMENT{f} '.mat']);
H10.(MOVEMENT{f}) = load(['D:\Toolkit\Backup\CRD-L-06022\c\Users\u0102306\Box Sync\DATA\PROCESSED_DATA\IDCA\IMU\H10\Mean_Subject_' ...
MOVEMENT{f} '.mat']);
H13.(MOVEMENT{f}) = load(['D:\Toolkit\Backup\CRD-L-06022\c\Users\u0102306\Box Sync\DATA\PROCESSED_DATA\IDCA\IMU\H13\Mean_Subject_' ...
MOVEMENT{f} '.mat']);
end
continue
end
Any suggestion is greatly appreciated!

Best Answer

The code you've posted indicates that your "variables" reside in separate .mat files, like
Mean_Subject_RF1.mat
Mean_Subject_RGV2.mat
The whole thing would be much easier if you re-organized how you store things so that the variables present for Hxx all reside in the same .mat file:
pth='D:\Toolkit\Backup\CRD-L-06022\c\Users\u0102306\Box Sync\DATA\PROCESSED_DATA\IDCA\IMU\';
save( fullfile(pth,'H18\MeanSubject.mat') , 'RF1','RGV2',...)
Then instead of loading the variables one-by-one, do
H18=load(fullfile(pth,'H18\MeanSubject.mat'));
This gives you, in a single command, a struct H18 containing all the variables (and only those variables) that were present for H18.
Related Question