How using a script of variables in a parfor loop ?
2 次查看(过去 30 天)
显示 更早的评论
Hello,
I have gathered the declaration of variables in one and the same script, to simply reduce the number of lines in the main function. The script of variables therefore contains:
Var1 = 2;
Var2 = 3;
....
The loop just reads the script.
parfor i = 1:5
scriptOfVariables
Var3 = Var1 + Var2
end
It seems that parfor does not accept it and I have to write the set of variables directly in the loop.
Any idea to avoid overloading the loop?
2 个评论
Ive J
2022-1-13
why not save/load the variables in/as mat/struct? Though not sure about overhead issues (should be fine if variables are few).
采纳的回答
Matt J
2022-1-13
编辑:Matt J
2022-1-13
Does scriptOfVariables use the loop counter i in any way? If not, you should move it outside the loop,
scriptOfVariables;
parfor i = 1:5
Var3 = Var1 + Var2;
end
Otherwise, you should be using a function instead
parfor i = 1:5
[Var1,Var2]=mfunction(i);
Var3 = Var1 + Var2;
end
4 个评论
Matt J
2022-1-15
From what I understand, Matlab cannot recognize structures declared outside the loop and used inside the loop.
No, that's not the problem. The problem is that you are not allowed to assign to variables declared outside the loop unless it is a sliced variable. However, you can return the struct from a function:
parfor i = 1:5
[S,Var1,Var2]=declareTemp();
Var3 = Var1 + Var2
struct.var(1).type = 6;
....
end
function [S,Var1,Var2]=declareTemp()
Var1 = 2;
Var2 = 3;
struct.var(1) = 5;
struct.var(2) = 7;
end
更多回答(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!