How to assign a value to specific locations of a matrix in MATLAB?
matlab, matrix, variable-assignment
Solution
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;
Problem
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,