Assigning multiple values to a matrix at locations specified by an array of indices?

73 views (last 30 days)
Consider that i have the following matrix:
my_mat = zeros(10,10);
To this matrix, I need to assign values (specified by variable "val") at specific locations defined by two arrays "x" and "y".
val = [98 99 100]; x = [1:3]'; y = [4:6]';
I need the following:
my_mat(1,4) = 98;
my_mat(2,5) = 99;
my_mat(3,6) = 100;
Trying to do the following (without using a loop) gives me matrix dimension error (left side 3x3 and right side 3x1):
my_mat(x,y) = val;
Is there anyway I could do this operation?

Accepted Answer

KSSV
KSSV on 23 Jun 2020
Read about sub2ind. This should be used for your case.
val = [98 99 100] ;
idx = sub2ind(size(my_mat),x,y) ;
my_mat(idx) = val ;

More Answers (0)

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!