简体   繁体   English

在MATLAB中从向量更改矩阵元素

[英]Change matrix elements from vectors in MATLAB

I have a matrix M containing just zeros. 我有一个矩阵M只包含零。 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. 现在,如果我说M(4), M(5) or M(2500) ,我希望结果在所有情况下都是1。

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. 请注意,这仅适用于线性索引 ,因此当您将50x50矩阵展平为一个2500x1向量时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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