I have a matrix say
Z = [1 2 3;
4 5 6;
7 8 9]
I have to change its values, say at positions (2,2) and (3,1), to some specified value. I have two matrices rowNos
and colNos
which contain these positions:
rowNos = [2, 3]
colNos = [2, 1]
Let's say I want to change the value of elements at these positions to 0.
How can I do it without using for loop?
Use sub2ind, it'll convert your sub-indices to linear indices, which is a number pointing at one exact spot in the matrix (more info).
If you want to operate on all elements on a specific row and column (elements in higher dimensions that is), you can also address them using linear indexing. It only becomes a bit trickier of calculating them:
experiment a bit with sub2ind, and go through my code step-by-step to understand it.
It would've been easier if it was the first dimension you wanted to take all elements off, then you could have used the colon operator
:
You would like to do this
but you can not - MATLAB does a Cartesian product of the indices. You can do this trick
Flatten the z-matrix and access it through a linear index, which is a combination of rowNos and colNos. Remember that MATLAB flattens the matrix by columns (column-based matrix storage).
Use
sub2ind
with multiple entries for rows and columnsExample: