如何更改矩阵中多个点的值?
我有一个矩阵 [500x500]。我有另一个矩阵 [2x100],其中包含可能位于第一个矩阵内的坐标对。我希望能够将第一个矩阵的所有值更改为零,而不需要循环。
mtx = magic(500);
co_ords = [30,50,70; 30,50,70];
mtx(co_ords) = 0;
I have a matrix that is [500x500]. I have another matrix that is [2x100] that contains coordinate pairs that could be inside the first matrix. I would like to be able to change all the values of the first matrix to zero, without a loop.
mtx = magic(500);
co_ords = [30,50,70; 30,50,70];
mtx(co_ords) = 0;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用函数 SUB2IND 将下标对转换为线性索引:
You can do this using the function SUB2IND to convert your pairs of subscripts into a linear index:
另一个答案:
Another answer:
当我在 3D 中寻找类似的问题时,我偶然发现了这个问题。我有行索引和列索引,并且想要更改与这些索引相对应的所有值,但在每个页面中(因此整个第三维)。基本上,我想执行 mtx(row(i),col(i),:) = 0;,但不循环遍历 row 和 col 向量。
我想我应该在这里分享我的解决方案,而不是提出一个新问题,因为它密切相关。
另一个区别是,我从一开始就可以使用线性索引,因为我使用
find
来确定它们。为了清楚起见,我将包括该部分。I've stumbled upon this question while I was looking for a similar problem in 3-D. I had row and column indices and wanted to change all values corresponding to those indices, but in each page (so the entire 3rd dimension). Basically, I wanted to execute
mtx(row(i),col(i),:) = 0;
, but without looping through the row and col vectors.I thought I'd share my solution here instead of making a new question since it's closely related.
One other difference was that linear indices were available to me from the start because I was determining them using
find
. I'll include that part for clarity's sake.