How to input global variables in function that is in parloop?
Afficher commentaires plus anciens
Hi.
I want to call some data ( = matrix) in function in parloop.
First time, I used global variable, but it is not worked in parloop.
How can I implement the code below without global variable?
The size of 'data1' is so large, so individually calling the data in function takes so much computing resources.
load('...\data1')
data1 = data1;
global data1
x = nchoosek([1:10], 2);
parfor i = 1:10
y(i) = myfunc(x(i, :));
end
% Function
function y = myfunc(x)
global data1
y = data1(x);
end
Réponse acceptée
Plus de réponses (1)
Another option is to use parallel.pool.Constant to arrange for the data to be loaded and then accessed. This can be a bit simpler than writing your own function using persistent data (behind the scenes it is basically the same thing though). Using the "function handle" constructor avoids transferring the data, and gets each worker to call load for itself. Here's a simple example:
parpool("local");
% This instructs each worker to load variable X from the file durer.mat and
% retain the value.
c = parallel.pool.Constant(@() load("durer.mat", "X"));
parfor i = 1:100
% Here's how you access the value - use "c.Value". The return from the
% "load" function is a struct, so we need to get the field "X" out of
% that struct
data = c.Value.X;
% Now we can operate on the data.
y(i) = sum(data(:,i));
end
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!