Passing a Global Variable to arrayfun for gpuArray

조회 수: 4 (최근 30일)
FARHAN ISLAM
FARHAN ISLAM 2021년 11월 3일
댓글: Jens Risbo 2022년 2월 17일
Hi,
I would like to pass a global array to the arrayfun function. While it does work with regular CPU array, it does not work with GPU array. My original code is quite complicated, but I am pasting a simplified code to help you understand what I am trying to do.
Any help on how this can be accomplished is greatly appreciated!
M = randi(500,100,100);
global a
a = [1 2 3];
tic
C = arrayfun(@function_sum,M);
CPUTime = toc
M = gpuArray(M);
tic
C = arrayfun(@function_sum,M);
GPUTime = toc;
Boost = CPUTime/GPUTime
function y = function_sum(x)
global a
y = 0;
for i = 1 : x
y = y + 1/i + 1*a(1) + 2*a(2) + 3*a(3);
end
end

채택된 답변

Edric Ellis
Edric Ellis 2021년 11월 4일
You can do this by using a nested function and variables in the containing parent workspace instead of global variables. Here's how you would apply this to your example. Note that I've made function_sum become a nested function, and it accesses a directly from the containing function workspace.
function repro
M = randi(500,100,100);
a = [1 2 3];
% Nested function
function y = function_sum(x)
y = 0;
for i = 1 : x
% Access 'a' directly from parent workspace
y = y + 1/i + 1*a(1) + 2*a(2) + 3*a(3);
end
end
tic
C = arrayfun(@function_sum,M);
CPUTime = toc
M = gpuArray(M);
tic
C = arrayfun(@function_sum,M);
GPUTime = toc;
Boost = CPUTime/GPUTime
end
There's a more detailed example of this approach here in the doc.
  댓글 수: 2
FARHAN ISLAM
FARHAN ISLAM 2021년 11월 5일
Thank you so much Edric! Your method worked and it lowered my calcualtion time on the original code that I am working with by a factor of 60.
Jens Risbo
Jens Risbo 2022년 2월 17일
Thanks for the example ! Just one Question.
Are these varables initialed everytime the nested function is called, or only once?
/Jens

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 GPU Computing에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by