Extra dimensions and CartesianIndices


I was wondering whether anyone has had to deal with “extra dimensions” while using ChartesianIndices. In particular, I am tempted to implement the following but it doesn’t work. Thanks in advance!

N = 2; M = 2; L = 2; K = 2;
X = rand(N,M);
Y = rand(N,M,L);
Z = rand(N,M,L,K);

function do_thing(X, Y, Z, k)
@inbounds for Index in CartesianIndices(X)
xi = X[Index];
for l = 1:L
Z[:, :, l, k] = xi + Y[Index, l];
return Z;

Let’s not use optimizations like @inbounds until the regular version is working.

X = rand(2,2);
Y = rand(2,2,2);
Z = rand(2,2,2,2);

function do_thing(X, Y, Z, iloc)
    for I in CartesianIndices(X)
        xi = X[I];
        for j in 1:2
            Z[:, :, j, iloc] = xi + Y[I, j];
return Z;

This fails with error:
julia> do_thing(X,Y,Z,2) ERROR: ArgumentError: indexed assignment with a single value to possibly many locations is not supported; perhaps use broadcasting .= instead?

Because you are doing:

Z[:, :, j, iloc] = xi + Y[I, j];

Your left hand side is an array, but the right-hand side is a number. If you want to set all the indices in the left to the single number, then following the suggestion will work

Z[:, :, j, iloc] .= xi + Y[I, j];

But, is this what you want to do?

Actually, I think just choosing the index in I works! Thanks!