Assigning multiple values to a matrix at locations specified by an array of indices?
28 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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?
0 commentaires
Réponse acceptée
KSSV
le 23 Juin 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 ;
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!