简体   繁体   中英

Change matrix elements from vectors in MATLAB

I have a matrix M containing just zeros. Now I have two arrays. The first one contains the indices of the matrix which need to be changed and the second one contains the values to which the elements of the matrix at those indices needs to be changed.

Let's say:

mat_A = zeros(50, 50);
vec_indices = [4; 5; 2500];
vec_values  = [1; 1; 1];

Now if I say M(4), M(5) or M(2500) , I want the result to be 1 in all cases.

Is there a simple "one-liner" that get's this task done?

Simple:

mat_A(vec_indices) = vec_values

Note that this only works like this for linear indices , so when you flatten your 50x50 matrix into one 2500x1 vector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM