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

68 visualizaciones (últimos 30 días)
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?

Respuesta aceptada

KSSV
KSSV el 23 de Jun. de 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 ;

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos


Versión

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by