Changing multiple elements (of known coordinates) of a matrix without a for loop

前端 未结 3 1909
南笙
南笙 2020-12-20 00:59

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 v

3条回答
  •  情歌与酒
    2020-12-20 01:55

    You would like to do this

    z(rowNos, colNos)
    

    but you can not - MATLAB does a Cartesian product of the indices. You can do this trick

    idx=(colNos-1)*size(z, 1)+rowNos;
    z(idx)=0
    

    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).

提交回复
热议问题