MATLAB: Issue with Multithreading in MATLAB

MATLAB and Simulink Student Suitemultithreading

Hello,
I have very long for loops i.e.
for i=1:109771
% Many steps
% STEP FOR APPENDING A MATRIX INTO A gif
end
Each step in for loop takes about 3 seconds. Is there a way to do this in parallel processing?
Can you please help me with an example. On how to modify this above code to get it working in a High Performance Computing environment.
On how many cores can I run this code?
Sincere Regards,
Sanchit

Best Answer

pool_cluster = 'myCluster';
numframes = 109771;
frame_rows = 512; %adjust as appropriate

frame_cols = 768; %adjust as appropriate
frame_panes = 3; %1 for grayscale or pseudocolor
cmap = []; %256 x 3 for pseudocolor
gif_frame_rate = 22; %fps
gif_delay = 1/gif_frame_rate;
gif_array = zeros(frame_rows, frame_cols, frame_panes, numframes, 'uint8');
myCluster = parcluster(pool_cluster);
parfor (frameidx = 1 : numframes, myCluster)
%many steps
thisframe = something_appropriate; %that is frame_rows x frame_cols x frame_panes
gif_array(:, :, :, frameidx) = thisframe;
end
if frame_panes == 1 %only valid for grayscale or pseudocolor
imwrite(gif_array, cmap, 'YourGifFileName.gif', 'DelayTime', gif_delay);
else %rgb has to be appended a frame at a time
imwrite(gif_array(:,:,:,1), cmap, 'YourGifFileName.gif', 'DelayTime', gif_delay, 'WriteMode', 'overwrite');
for frameidx = 2 : numframes
imwrite(gif_array(:,:,:,frameidx), cmap, 'YourGifFileName.gif', 'DelayTime', gif_delay, 'WriteMode', 'append');
end
end
"On how many cores can I run this code?"
The above code is for the case where you have a Distributed Computing license and a cluster named myCluster has been configured. The number of cores that would be used would depend upon what was specified in the cluster profile. It is common for the number of cores configured in a profile is the number of physical cores on the cluster, but other numbers could be configured for economic or policy reasons.