How to assign value to specific matrix locations in MATLAB?

I am not very familiar with Matlab, so I apologize in advance for this stupid question. I would like to assign number 1 to some specific matrix locations. I have a row vector and corresponding column vector. I tried to assign values ​​to these places several times. However, this did not work. Smaller code example. Suppose that there is a 4 * 4 matrix, and I would like to set the 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 received the 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'm doing wrong here? The actual size of the matrix I'm going to work on is thousands, so I cannot manually assign these positions manually. Is there a way to use row vector and column vector, do I need to set the value to 1? Thank you very much,

+6
source share
3 answers

You can use sub2ind to calculate the linear indexes of the positions you want to assign, and use them to assign:

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

A bit of relief. If you are not running multiple non-contiguous rows or columns, a very useful way is similar to

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

It supports element math very easily.

it would turn

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

in

 {0 1 1 1} {0 1 1 1} {0 1 1 1} {0 0 0 0} 
+1
source

All Articles