How to run a for loop multiple times on some images?
37 views (last 30 days)
Show older comments
Hello,
I am very new to Matlab. I am trying to create a loop to read four images in a file. However, I cannot repeat the for a loop several times. I need to present these 4 images 32 times randomly (each image 8 times). I appreciate it if you help me. This is the code I am already using:
nTrials = 4
for i = 1:nTrials
trial{i} = imread(['A' num2str(i) '.jpg']);
end
fixation = imread('fixation.jpg');
Screen('Preference', 'VisualDebugLevel', 1);
window = Screen('OpenWindow', 0, [100 100 100])
for i = 1:nTrials
texture = Screen('MakeTexture', window, fixation);
Screen('DrawTexture', window, texture);
Screen('Flip', window);
WaitSecs(0.5)
texture = Screen('MakeTexture', window, trial{i});
Screen('DrawTexture', window, texture);
Screen('Flip', window);
WaitSecs(1.5)
end
sca;
nTrials is equal to 4 (since i have just 4 images) but when i change it to more than 4 i receive this error:
imread: unable to find file 'A5.jpg'
0 Comments
Answers (2)
KSSV
on 22 Aug 2022
n = repmat(1:4,1,8) ;
idx = randsample(length(n),length(n)) ;
n = n(idx) ;
Run a loop on n, 1:4 stand for the four images respectovely.
Image Analyst
on 22 Aug 2022
That file does not exist. Get a list of files that actually exist with dir():
% Get list of files that are in the folder.
fileList = dir('A*.jpg')
if isempty(fileList)
warningMessage = sprintf('Folder has no JPG images');
uiwait(errordlg(warningMessage));
return;
end
% Get all filenames in a list
allFileNames = {fileList.name};
nTrials = length(allFileNames)
% Read in all the images and display them.
for k = 1:nTrials
trial{k} = imread(allFileNames{k});
imshow(trial{k});
drawnow;
end
See Also
Categories
Find more on Image display and manipulation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!