如何更改矩阵中多个点的值?

发布于 2024-11-26 19:13:43 字数 181 浏览 0 评论 0原文

我有一个矩阵 [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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

放血 2024-12-03 19:13:43

您可以使用函数 SUB2IND 将下标对转换为线性索引:

mtx(sub2ind(size(mtx),co_ords(1,:),co_ords(2,:))) = 0;

You can do this using the function SUB2IND to convert your pairs of subscripts into a linear index:

mtx(sub2ind(size(mtx),co_ords(1,:),co_ords(2,:))) = 0;
戴着白色围巾的女孩 2024-12-03 19:13:43

另一个答案:

mtx(co_ords(1,:)+(co_ords(2,:)-1)*500)=0;

Another answer:

mtx(co_ords(1,:)+(co_ords(2,:)-1)*500)=0;
删除会话 2024-12-03 19:13:43

当我在 3D 中寻找类似的问题时,我偶然发现了这个问题。我有行索引和列索引,并且想要更改与这些索引相对应的所有值,但在每个页面中(因此整个第三维)。基本上,我想执行 mtx(row(i),col(i),:) = 0;,但不循环遍历 row 和 col 向量。

我想我应该在这里分享我的解决方案,而不是提出一个新问题,因为它密切相关。

另一个区别是,我从一开始就可以使用线性索引,因为我使用 find 来确定它们。为了清楚起见,我将包括该部分。

mtx = rand(100,100,3); % you guessed it, image data
mtx2d = sum(mtx,3); % this is similar to brightness
ind = find( mtx2d < 1.5 ); % filter out all pixels below some threshold

% now comes the interesting part, the index magic
allind = sub2ind([numel(mtx2d),3],repmat(ind,1,3),repmat(1:3,numel(ind),1));
mtx(allind) = 0;

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.

mtx = rand(100,100,3); % you guessed it, image data
mtx2d = sum(mtx,3); % this is similar to brightness
ind = find( mtx2d < 1.5 ); % filter out all pixels below some threshold

% now comes the interesting part, the index magic
allind = sub2ind([numel(mtx2d),3],repmat(ind,1,3),repmat(1:3,numel(ind),1));
mtx(allind) = 0;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文