It is extremely inefficient to do so in a nested loop in Matlab.
Using sub2ind
can help you do so much faster:
y( sub2ind( size(y), i, j ) ) = 1;
EDIT - sub2ind
What sub2ind
does?
Suppose you have a matrix M
of size [4 6]
:
M = [ 1 5 9 13 17 21
2 6 10 14 18 22
3 7 11 15 19 23
4 8 12 16 20 24 ];
You wish to access two elements: the one at the first row and second column, and another at the fourth row and the fifth column.
In that case you have the rows you wish to access r = [ 1 4 ]
and the columns you wish to access c = [ 2 5 ]
. However, if you try and access
>> M( r, c )
This is a 2x2 matrix
ans =
5 17
8 20
And not the two elements you were looking for (which are 5
and 20
).
What sub2ind
does is convert the row/column indices you have into linear indices
>> sub2ind( size(M), r, c )
ans =
5 20
which happens to be the linear indices of the requested entries.
You can think of linear indices as the single index required to access an element in a matrix in the case that the matrix was converted to a vector stacking its columns one after the other.
A few comments:
Matlab has a few ways of indexing matrices: by row / column indices (like i
and j
in your question). By linear indices (like index
in your question). However, the more efficient way is to use logical indexing: that is, using a matrix of the same size as y
with true
for the entries you wish to set / get.
So, in your example, if you could get such a logical matrix instead of index
or i
and j
it would have been better.
Matlab has many advantages over other programing languages. One of them is its ability to perform vector/matrix operations extremely efficient. Resorting to loops, or worse, nested loops, is something that should be avoided in Matlab.
It is not a good practice to use i
and j
as variables in Matlab.