(revised) What is the right way to apply parallel.pool.Constant on functional handle?

(original question) I use parfor-loop to process through rows of table/array. In each iteration, a function handle is called to do that. But this leads to a warning message that the function handle is 'a broadcast variabe' and might 'result in unnecessary communication overhead.' Is there a solution to avoid that?
(revised question) I tried parallel.pool.Constant(function_handle), and it generates an error message when calling the function: "Error using [my iteration function]. Unable to use a value of type string as an index." What is the right way to use parallel.pool.Constant(function_handle)?
function res = iteration(f, A)
% f is a function handle
C = cell(height(A),1);
parfor row = 1:height(A)
C{row} = f(A{row,:}); % f is a broadcast variable
end
res = vertcat(C{:});
end

4 Comments

In the help page for broadcast variable, I found a pitential solution: parallel.pool.Constant
I don't know the proper way to use parallel.pool.Constant. My codes generate an error message, "Unable to use a value of type string as an index."
function res = iteration(f, T)
% f is a function handle
C = cell(height(T),1);
%%%%%% adding this line would generate an error message
fh = parallel.pool.Constant(f);
parfor row = 1:height(T)
fh(T{row,:})
C{row} = f(T{row,:});
end
res = vertcat(C{:});
end
If I assign the pool constant by itself in the live editor, I get a different error message: "Not enough input arguments."
% bad codes
fc = parallel.pool.Constant(@(x) x{1})
I think I don't really know how parallel.pool.Constant should work. The document says it should be used in a Matlab client session. I run the codes in my local computer, so that probably is not the problem.
function res = iteration(f, T)
% f is a function handle
C = cell(height(T),1);
%%%%%% adding this line would generate an error message
fh = parallel.pool.Constant(f);
parfor row = 1:height(T)
C{row} = fh.Value(T{row,:});
end
res = vertcat(C{:});
end
Note: see also rowfun
@Walter Roberson Thanks for your help. Glad to learn a new thing. As for rowfun, I used it before but found it was too cumbersome in terms of input arguments. And it does not allow parfor, so I try to make a simpler parfor version for my own usage.

Sign in to comment.

 Accepted Answer

I think I found the solution: feval(). It's in the help page of broadcast variable and parfor.
function res = iter_test(f, T)
% f is a function handle
C = cell(height(T), 1);
parfor row = 1:height(T)
C{row} = feval(f, T{row, :});
end
res = vertcat(C{:});
end

More Answers (0)

Categories

Products

Release

R2023a

Asked:

on 26 Jul 2023

Commented:

on 27 Jul 2023

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!