array assignment using an array as indexes


#1

I’m new to Julia and am trying to assign to a constant to locations in a multidimensional array using indexes specified in another array. I can do this with a for loop easily, but am trying to understand how to do it as a comprehension or something else without the loop.

For example:
a = reshape(1:25,5,5)’
5×5 Adjoint{Int64,Base.ReshapedArray{Int64,2,UnitRange{Int64},Tuple{}}}:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25


#2

If you want to change a, then you run into obvious trouble:

julia> a = reshape(1:25,5,5)';

julia> a[1,2]=3
ERROR: indexed assignment fails for a reshaped range; consider calling collect

It even tells you how to fix that:

julia> a = reshape(collect(1:25),5,5)';

julia> a[1,2]=3
3

Or were you asking about:

julia> A=reshape(collect(1:25), 5, 5);
julia> idxs=3:17;
julia> A[idxs].=-1;
julia> idxs=[1,2,25];
julia> A[idxs] = -10:-8;
julia> A
5×5 Array{Int64,2}:
 -10  -1  -1  -1  21
  -9  -1  -1  -1  22
  -1  -1  -1  18  23
  -1  -1  -1  19  24
  -1  -1  -1  20  -8

#4

Thanks, I didn’t realize this post went through. I had just setup my account and accidentally posted this without finishing writing it. I answered my own question shortly after. Your second answer is closer to what I was looking for.

I was trying to assign a to locations in an array where the locations where specified in another array. For example:

a = zeros(Int64,5,5)
y=[1,2,2,5,5]
one_locs = [CartesianIndex(i,y[i]) for i in 1:length(y)]
a[one_locs] .= 1
5×5 Array{Int64,2}:
1 0 0 0 0
0 1 0 0 0
0 1 0 0 0
0 0 0 0 1
0 0 0 0 1

My question was more about how to use the CartesianIndex and what I was having trouble with was I didn’t realize I needed the .= for the assignment.