简体   繁体   中英

How to assign a value to specific locations of a matrix in MATLAB?

I am not very familiar with Matlab so apologize for this silly question in advance. I would like to assign number 1 to some specific locations of a matrix. I have a row vector and the corresponding column vector. I tried to assign values to these locations several times. However, it didn't work. Here is a smaller size codes example. Assume there is a 4*4 matrix and I would like to assign matrix(1,1), matrix(2,3) and matrix (3,4) to 1. This is what I did.

matrix = zeros(4,4);
row = [1 2 3];
col = [1 3 4];
matrix(row,col)=1;

However, I got answer as

matrix=[ 1 0 1 1
         1 0 1 1
         1 0 1 1
         0 0 0 0]    

Can someone point out what I do wrong here? The actual size of the matrix I am going to work on is in thousands so it is why I can not assign those positions one by one manually. Is there any way to use the row vector and column vector I have to assign value 1 ? Thank you very much,

You can use sub2ind to compute the linear indices of the positions you want to assign to and use those for the assignment:

indices = sub2ind(size(matrix), row, col);
matrix(indices) = 1;
matrix(1,1) = 1
matrix(2,3) = 1
matrix(3,4) = 1

A bit of a bump. Unless you are doing quite a few noncontiguous rows or columns, a very useful way is like

matrix(1:3,2:4)=1

It supports element math very easily

this would turn

{0 0 0 0}
{0 0 0 0}
{0 0 0 0}
{0 0 0 0}

into

{0 1 1 1}
{0 1 1 1}
{0 1 1 1}
{0 0 0 0}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM