# Extra dimensions and CartesianIndices

**URL:** <https://discourse.julialang.org/t/extra-dimensions-and-cartesianindices/97665>\
**Category:** General Usage\
**Tags:** indexing\
**Created:** [April 19, 2023, 4:48pm UTC](https://discourse.julialang.org/t/extra-dimensions-and-cartesianindices/97665 "2023-04-19T16:48:40Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![danicaratelli](https://avatars.discourse-cdn.com/v4/letter/d/90db22/32.png) [@danicaratelli](https://discourse.julialang.org/u/danicaratelli)\
**Post date:** [April 19, 2023, 4:48pm UTC](https://discourse.julialang.org/t/extra-dimensions-and-cartesianindices/97665/1 "2023-04-19T16:48:40Z")

</div>

Hello,

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];  
> end  
> end  
> return Z;  
> end

---

<div class="post-metadata">

**Author:** ![aramirezreyes](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/aramirezreyes/32/42573_2.png) [@aramirezreyes](https://discourse.julialang.org/u/aramirezreyes)\
**Post date:** [April 19, 2023, 5:08pm UTC](https://discourse.julialang.org/t/extra-dimensions-and-cartesianindices/97665/2 "2023-04-19T17:08:48Z")

</div>

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

```julia
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];
        end
    end
return Z;
end

```

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:

```julia
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

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

```

But, is this what you want to do?

---

<div class="post-metadata">

**Author:** ![danicaratelli](https://avatars.discourse-cdn.com/v4/letter/d/90db22/32.png) [@danicaratelli](https://discourse.julialang.org/u/danicaratelli)\
**Post date:** [April 19, 2023, 5:35pm UTC](https://discourse.julialang.org/t/extra-dimensions-and-cartesianindices/97665/3 "2023-04-19T17:35:17Z")

</div>

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