- Does MATLAB error out?
- Does the file get created, but it doesn't contain the variable?
- Does it contain the variable but the variable doesn't contain the entire value?
Matlab Transparency violation error while the code is correct
2 ビュー (過去 30 日間)
古いコメントを表示
I have a problem with a code i wrote, The whole code consist 6 for-loops and every itteration took forever to complete so I tried it with a parfor.
every itteration is independent but I need to save the result from each one, so it supposed to save the results in vector 'v', and export it to a function that supposed to save a matrix with the vector 'v' in its place.
The code is correct and it runs, but it doesn't save the matrix.
The code is:
parfor j = 1 : endrun
**other 5 fors * *
5 ends
v(1)=a;
...
v(10)=k;
mySave('ResMat.mat', v , j);
end
function mySave(filenm, v, j)
ResMat( j, :) = v;
save(filenm, 'ResMat', '-mat');
end
Will be grateful for help, and if you have other way to do that or maybe a way to make it much efficient, every tip will be great.
Thank you
2 件のコメント
Raymond Norris
2022 年 4 月 5 日
Can you elaborate more when you say it doesn't save?
mySave overwrites ResMat each time you call it, so I don't see ResMat getting updated properly. Plus, what happens when two workers try writing to the same MAT-file (ResMat.mat) at the same time?
回答 (1 件)
Dheeraj
2024 年 1 月 8 日
Hi,
I understand that you are not getting expected results while using “parfor” from Parallel Computing Toolbox.
When using “parfor” in MATLAB, it's important to note that each iteration of the loop runs independently on a separate worker, and therefore, you need to be careful about updating shared variables. In your case, the variable “ResMat” is being updated independently by each worker, leading to potential race conditions and overwriting.
To address this issue, you can use “spmd” (Single Program Multiple Data) to accumulate results from each worker and then save the final result after the parallel loop or alternatively you could use temporary variable to save results from each loop and after the loop completion combine all results and store them in “ResMat”.
The below code demonstrates one way of doing it.
% Preallocate ResMat outside the parfor loop
% Adjust the size based on your actual data size
ResMat = zeros(endrun, 10);
parfor j = 1:endrun
% Your code here
v(1) = a;
% ...
v(10) = k;
% Save results to a temporary variable for each iteration
tempResMat(j, :) = v;
end
% Consolidate the results from all workers
ResMat = tempResMat;
% Save the final matrix outside the parfor loop
save('ResMat.mat', 'ResMat', '-mat');
You could refer to the below MATLAB’s documentation to know more about “spmd”
Hope this helps!
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Parallel for-Loops (parfor) についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!