## Broadcast variables in parfor loop in MATLAB

Problem Description:

The following loop results in an error in `C_mat`

and `B_mat`

:

```
%previously defined
N_RIPETIZIONI=2;
K=201;
parfor n=1:N_RIPETIZIONI*K
[r,k]=ind2sub([N_RIPETIZIONI,K],n);
B=B_mat{r};
C=C_mat{r};
end
```

The warning says:

The entire array or structure B_mat is a broadcast variable. This might result in unnecessary communication overhead.

The same for `C_mat`

.

How can I fix it so that the indices of `B_mat`

and `C_mat`

are no more broadcast variables?

## Solution – 1

The issue is that the way you index `B_mat`

(i.e. not using `n`

), every thread in the `parfor`

requires the entirety of `B_mat`

to run. The big bottleneck in parfor code is transferring copies of the data to each node.

MATLAB is basically telling you that if you were to do this, you may actually have slower code than otherwise. Its not that `B_mat`

is some type of variable called "broadcast", its that the way you wrote the code, each `n`

in parfor requires a copy of `B_mat`

.

I assume this is not your real code, so we can’t really help you fix it, but hopefully this explains it.