How can I save a variable of type cell or higher dimensional matrix with different filenames inside a parfor loop?
4 views (last 30 days)
Show older comments
madhurima bhattacharjee
on 16 Oct 2024
Commented: madhurima bhattacharjee
on 17 Oct 2024
How can I save a variable of type cell or higher dimensional matrix with different filenames inside a parfor loop?. I use MATLAB version 2021. So I don't have acces to the new "formstruct" option which is availabe from MATLAB version 2024a. I defined a fuction parsave and called it inside the parfor loop to save my variables with different filenames. But it works only if the variable is a two dimensional matrix.
2 Comments
Damian Pietrus
on 16 Oct 2024
What's the error that you get when you try to save the file? Including a code snippet of the save function and where you call it in your parfor loop would be helpful.
Accepted Answer
Hitesh
on 17 Oct 2024
Hi Madhurima,
You can save variables with different filenames by creating a separate function to handle the file-saving process when working with "parfor" loops. Since you are dealing with cell arrays or higher-dimensional matrices, you need to ensure that "parsave" function can handle these data types appropriately. Kindly refer to the below code for an example:
parfor i = 1:5
% Create a cell array or higher-dimensional matrix
myCellArray = {rand(3), rand(3)}
my3DMatrix = rand(3, 3, 3)
% Generate a filename for each iteration
cellFilename = sprintf('cellArray_%d.mat', i);
matrixFilename = sprintf('matrix3D_%d.mat', i);
% Save using the parsave function
parsave(cellFilename, myCellArray);
parsave(matrixFilename, my3DMatrix);
end
function parsave(filename, var)
save(filename, 'var');
end
If the issue persists, could you please share the code file where you are encountering any error? So that I can investigate the issue.
For more information regarding, refer to this MATLAB documentation:
More Answers (0)
See Also
Categories
Find more on Parallel for-Loops (parfor) 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!