How to run two functions simultaneously where one uses the outputs from the other to then store the data into a matrix/ vector?
2 次查看(过去 30 天)
显示 更早的评论
I am trying to run two functions simultaneously where the first function's outputs can be used for the second function, but the problem is that I need the second function's output to be saved into a matrix or vector as this is the data I ultimately need.
The first function runs through 20 different data sets to give 20 sets of outputs. Then, I want the second function to use 2 of these outputs as inputs for the final solution for each set. Ultimately, I'll have a vector/matrix of 20 numbers.
I'm not sure which set of loops I need. I know I need a for loop, but the next one I am unsure of.
nP=20;
for iP=1:nP;
InvertElastic(Profile(iP).x,transpose(Profile(iP).t),Atest,xq,Mm,Mt,Profile(iP).v200,Ps); % First function
loadthicknessness(iP)=loadsize(A(iP),Q(iP)); %Second function
end
1 个评论
Walter Roberson
2019-2-24
We recommend against using load as the name of a variable, as that interfers with using the MATLAB load() function and confuses readers of your code.
回答(1 个)
Walter Roberson
2019-2-24
You would need the Parallel Computing Toolbox. You would probably use spmd . The code outline would look like
parpool(2)
spmd
if labindex == 1
for iP = 1 : nP
do first computation for index iP
labSend(results_of_first_function, 2);
end
else
for iP = 1 : nP
results_of_first_computation = labReceive(1);
do second computation
saved_results(iP,:) = whatever;
end
end
This code would have the second worker sit idle waiting for the first iteration of the first worker to finish. When the first worker finishes the first iteration it would send data to the second worker which would work on it simulatenously with the first worker processing the second iteration.
It is common for the overhead of sending data between workers to be more costly than running everything in serial. It is common for the reduction to one thread per worker that (usually) happens automatically to result in the computation taking longer to finish than if you ran in serial.
Running two tasks "simultaneously" is not always better: but the above is an outline of how you can do it.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!