Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 363
Cassie Avatar asked Apr 08 '13 05:04

Cassie


2 Answers

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;
like image 165
Bjoern H Avatar answered Sep 18 '22 01:09

Bjoern H


matrix(1,1) = 1
matrix(2,3) = 1
matrix(3,4) = 1
like image 24
Petar Ivanov Avatar answered Sep 22 '22 01:09

Petar Ivanov