How to parallelize access to cell array

조회 수: 19 (최근 30일)
Su Aung
Su Aung 2017년 2월 9일
답변: Jan 2017년 2월 10일
Hello, I have a cell array of size 160X240. I have to do some complex calculation on each and every elements of this array. I would like to do this calculation in parallel to make it quicker because it is too slow right now. I previously write my code with nested for loop and call a function which do calculation on (row,col) element.
global c;
c = cell(160,240);
for row = 1:160
for col = 1:240
calculation(row,col);
end
end
function calculation(row,col)
global c;
c{row,col} = do something;
function anotherFunction()
global c;
also do something on c's {row,col} element
function 'calculation' and' anotherFunction' are written on another .m files. And the whole work is also repeated. So I have to use global variable to share c between these .m files. I've tried to replace inner for loop with parfor loop and It's seem that function calculation doesn't know the global c anymore. Could anyone tell me how can I parallelize my work here (or it is even possible). I am new to parallel processing and I've tried to read some article and examples about it. But I couldn't get what I want exactly. I really appreciate any help I could get. Thank you....
Su Aung

채택된 답변

Edric Ellis
Edric Ellis 2017년 2월 10일
The workers that execute the body of parfor loops are separate MATLAB processes, and there is no automatic synchronisation of global variables between the processes. To fix this, you need to explicitly pass in c to your function.
To run in parallel, you'll need to modify your code so that instead of placing the results in the global c, they are returned from your function.

추가 답변 (1개)

Jan
Jan 2017년 2월 10일
Imagine the code as a real 3D setup: The global data are cards on one table, the threads are persons trying to use the data. You can expect collisions, when the global data are process synchronously. As Edric has said already, the solution is to avoid global data, but use input and output arguments, such that each thread knows, that he can access his data individually.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by