2
$\begingroup$

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.

Let`s 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}}

I`ve 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?

$\endgroup$
3
  • $\begingroup$ You can add matrices in Mathematica. CC += Kepf; should be much faster. $\endgroup$
    – C. E.
    Commented Mar 7, 2015 at 11:48
  • $\begingroup$ Yes I know, but these are not the same dimension matrices so it is not possible. $\endgroup$
    – Bartek
    Commented Mar 7, 2015 at 11:54
  • $\begingroup$ 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. $\endgroup$
    – C. E.
    Commented Mar 7, 2015 at 11:55

1 Answer 1

2
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.