0
votes

So I am trying to create a multidimensional array in Julia and I am not sure whether it is smarter/easier to store it in a vector or not. Let's say I have a (M x M x M x .... x M) matrix with N factors, so in total (M^N) entries. Now, I run a separate program which gives me indices e.g

ind = [1, 2, 4, 4, 5, ....., 2]

and all I would like to do is to update my matrix A (or vector) at this given index.

So for example I would like to do something like this:

index = [2,1,2]
A = reshape(collect(1:8),(2,2,2))
A[index] = 4

but what I really have to do is

A[2,1,2] = 4

or

A[index[1],index[2],index[3]] = 4

However, this solution is infeasible, since the number of dimensions varies and is very large in my application. I am using Julia v0.6.4 and found out that there is a function called sub2ind (which was replaced by a similar function in newer versions). However, this function only takes single numbers, separated by commas, which are neither arrays nor tuples (According to the documentation: )

sub2ind(dims, i, j, k...) -> index

How do I handle this problem appropriately/efficiently? Any help would be greatly appreciated!

1
Splatting is the right way to go, but also consider whether your program can return the indices as a tuple (ind = (1, 2, 4, 4, 5, ....., 2)) instead of a vector (ind = [1, 2, 4, 4, 5, ....., 2]), since a tuple will be considerably faster here.DNF

1 Answers

6
votes

You can splat the index vector:

A[index...] = 4