How to parallelize access to cell array

21 Ansichten (letzte 30 Tage)
Su Aung
Su Aung am 9 Feb. 2017
Beantwortet: Jan am 10 Feb. 2017
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

Akzeptierte Antwort

Edric Ellis
Edric Ellis am 10 Feb. 2017
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.

Weitere Antworten (1)

Jan
Jan am 10 Feb. 2017
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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by