#### [ manipulating indices of matrix in parallel in matlab ]

Suppose I have a m-by-n-by-p matrix "A", each indices stores a real number, now I want to create another matrix "B" and B(i, j, k) = f(A(i, j, k), i, j, k, otherVars), is there a faster way to do it in matlab rather than looping through all the elements? (notice the function requires the index number (i, j, k))

An example is as follows(The actual function f could be more complex):

```
A = rand(3, 4, 5);
B = zeros(size(A));
C = 10;
for x = 1:size(A, 1)
for y = 1:size(A, 2)
for z = 1:size(A, 3)
B(x, y, z) = A(x,y,z) + x - y * z + C;
end
end
end
```

I've tried creating a cell "B", and

```
B{i, j, k} = [A(i, j, k), i, j, k];
```

I then applied cellfun() to do the parallel computing, but it's even slower than a for-loop over each elements in A.

In my real implementation, function f is much more complex than B = A + X - Y.*Z + C; it takes four scaler values and I don't want to modify it since it's a function written in an external package. Any suggestions?

# Answer 1

Vectorize it by building an `ndgrid`

of the appropriate values:

```
[X,Y,Z] = ndgrid(1:size(A,1), 1:size(A,2), 1:size(A,3));
B = A + X - Y.*Z + C;
```