7

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,

Cassie
  • 1,179
  • 6
  • 18
  • 30

3 Answers3

10

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;
Bjoern H
  • 600
  • 4
  • 13
1
matrix(1,1) = 1
matrix(2,3) = 1
matrix(3,4) = 1
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
  • 2
    Thank you very much for replying. However, the actual size of my matrix is in thousands. I can not assign one by one. So is there anyway to use the row vector and column vector I have ? Thanks – Cassie Apr 08 '13 at 05:53
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}
Rudy
  • 11
  • 2