# How to assign a set of coordinates in Matlab?

I have three vectors in Matlab, i (integers), J (integers) and V (doubles). I want to assign to matrix at positions I_i, J_i, starting at i, the value V_i.

Is it possible? The problem is that A (I, J) refers to all possible combinations (I_i, J_j) instead of matching elements in the vector.

source to share

The short answer is this:

`A(sub2ind(size(A),X,Y)) = V`

Try it, it works like a charm.

Explanation, if you are curious and need it, just follow:

Each matrix in Matlab is stored as a 1d array, a normal vector.

The 2nd array is actually stored in memory as a sequence of the first column, then the second column, etc. Because of this, you can index any Matlab array, regardless of its dimension, with a linear index.

For example:

```
A = [1 4 7;
2 4 8;
3 6 9 ];
```

Actually saved as:

```
[1 2 3 4 5 6 7 8 9]
```

So, to access an item, all you have to do is: (j-1) * num_of_columns + i

Because of this, A (2,3) returns the same as A (8), that is, in this case: 8;

The sub2ind function converts the list of "indices" to linear indices based on the size of the matrix. Exactly what you want to do.

And with indexes, it's easy to get the job done.

Docs: sub2ind

I hope I understood you correctly.

I took a long time to answer because this is a very important part of Matlab, and a lot of people are recompiling the code using vector-work functions to do what can be done with normal indexing.

source to share

Try using ACCUMARRAY :

```
M = accumarray([I(:) J(:)], V(:));
```

In this case, if you have unique combinations of i and J, the corresponding values in V will be added together (the default functin function `@sum`

). If you need different behavior, pass the function as an optional argument `accumarray`

(see documentation ).

source to share

Perhaps you want to use a sparse matrix format? A = sparse (...) has a signature that can be used to coerce your (i, j, value) triplets into non-zero A values, where the other entries are structural zeros (no storage required).

If I asked a question, that is.

I think it will be something like A = sparse (i, j, v), the rest of the arguments will default to m: = max (i), n: = max (j), nzmax: = length (v) which is what I assume you want.

source to share