7
votes

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,

3
Thank you very much. I checked the post and it is very helpful.Cassie

3 Answers

10
votes

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;
1
votes
matrix(1,1) = 1
matrix(2,3) = 1
matrix(3,4) = 1
1
votes

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}