running a file from inside a parfor loop
16 次查看(过去 30 天)
显示 更早的评论
Malte Eggers
2020-3-29
评论: Thiago Henrique Gomes Lobato
2020-3-29
I'm doing a parameter sweep on a transfer function which is constructed from a lenghty statement that I'm printing to a file from sympy, which calculates the transfer function based on workspace variables. Without parallel computing, I just use
run('Gcl_tf.m')
I've tried to read the file to a string and eval'ing it from the parfor loop, unfortunately eval doesn't seem to like parfor. I could find information on how to attach a file to a parallel pool, but I can't figure out how to execute a file from those attached files.
I could of course just copy the file contents into my script, that works, but the line is so long that MATLAB doesn't display it properly. And in case I update the file, I'd have to copy it again.
0 个评论
采纳的回答
Thiago Henrique Gomes Lobato
2020-3-29
The main problem is that parfor can not tell from which workspace the variables should be used since you have many. You can solve this problem by actually creating a function from your file, something as:
function varargout = Gcl_tf(varargin)
...
% Your function
end
And then, from your parfor code, call the function passing only the variables you need
parfor idx=1:Iterations
...
TransferFunction = Gcl_tf(input);
...
end
2 个评论
Thiago Henrique Gomes Lobato
2020-3-29
Unfortunately you will not be able to have a solution like this in parfor due to the complication in finding the right workspace for each loop. The fact that it works without parfor actually doesn't mean much when you try to do things in parallel. I would strongly advise you to use the function approach even if you plan to make changes in the future since it is so much cleaner from a programming perspective. If you really want to call an extra file the only workaround I can think around is to trick the parfor with something like this:
parfor ...
workspace = runFile(workspace)
end
function workspace = runFile(workspace)
run('Gcl_tf.m')
end
You'll have to define the variable/structure workspace, do the necessary changes in your code and the code will be way more complex, but it will work in the way you want.
更多回答(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!