# Changing a Part of a variable within ParallelDo

I want to evaluate nested do as a parallel computations. My formula looks like:

Do[
Do[
CC[[i, j]] += Kepf[[i, j]],{j, 1, Dimensions[Kepf][[2]]}
],{i, 1, Dimensions[Kepf][[1]]}
]


When previously I created 0 matrix CC and some matrix Kepf. I just want to insert matrix Kepf into matrix CC. When the matrices are very large it takes some time. So I want use parallel computations to shorten time.

Lets consider a numerical example:

I create matrix A:

A = Table[0, {4}, {4}]


{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}

and matrix B:

B = Table[2 i + j, {i, 1, 2}, {j, 1, 2}]
{{3, 4}, {5, 6}}


then I evaluate the code

Do[A[[j]][[i]] += B[[i]][[j]], {i, 1, 2}, {j, 1, 2}]
{{3, 5, 0, 0}, {4, 6, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}


Ive got what I wanted, but when I try to do parallel computing using the code

SetSharedVariable[A, B]
ParallelDo[A[[j]][[i]] += B[[i]][[j]], {i, 1, 2}, {j, 1, 2}]


It says that:

(kernel 2) Part::wrsym: Symbol A is Protected.
(kernel 1) Part::wrsym: Symbol A is Protected.
(kernel 2) Part::wrsym: Symbol A is Protected.
(kernel 1) Part::wrsym: Symbol A is Protected.


Any idea?

• You can add matrices in Mathematica. CC += Kepf; should be much faster. Commented Mar 7, 2015 at 11:48
• Yes I know, but these are not the same dimension matrices so it is not possible. Commented Mar 7, 2015 at 11:54
• Then use CC[[;;dimx,;;dimy]] += Kepf; where dimx and dimy are the dimensions of Kepf. Under no circumstance should you be adding matrices using Do. You can also use ArrayPad for this. Commented Mar 7, 2015 at 11:55

With

a = Table[0, {4}, {4}]
b = Table[2 i + j, {i, 1, 2}, {j, 1, 2}]


using

SetSharedVariable[a]
ParallelDo[a[[j, i]] += b[[i, j]], {i, 1, 2}, {j, 1, 2}]
a

{{3, 5, 0, 0}, {4, 6, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}


would work, but using

a += Transpose[b] ~PadRight~ Dimensions@a

{{3, 5, 0, 0}, {4, 6, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}


is much nicer and faster.