在MATLAB中选择具有索引矩阵的值?(Select values with a matrix of indices in MATLAB?)

编程入门 行业动态 更新时间:2024-10-26 19:36:34
在MATLAB中选择具有索引矩阵的值?(Select values with a matrix of indices in MATLAB?)

在MATLAB中,我正在寻找一种通过从给定“选择器矩阵”的多个矩阵中进行选择来填充矩阵的有效(和/或矢量化)方法。 例如,给定三个源矩阵

M1 = [0.1, 0.2; 0.3, 0.4] M2 = [1, 2; 3, 4] M3 = [10, 20; 30, 40]

和一个指数矩阵

I = [1, 3; 1, 2]

我想生成一个新的矩阵M = [0.1, 20; 0.3, 4] M = [0.1, 20; 0.3, 4] ,从M1选择第一个条目,从M3选择第二个条目,等等。

我完全可以在嵌套循环中做到这一点,通过每个条目并填写价值,但我相信有一种更有效的方法。


如果M1 , M2 , M3和M都是3D矩阵(RGB图像)会怎么样? I每个条目都告诉我们,我们应该从哪个矩阵中选取一个3维向量。 假如I(1, 3) = 3 ,那么我们知道由M的(1, 3, :)索引的条目应该是M3(1, 3, :) 。

In MATLAB, I am looking for an efficient (and/or vectorized) way of filling a matrix by selecting from multiple matrices given a "selector matrix." For instance, given three source matrices

M1 = [0.1, 0.2; 0.3, 0.4] M2 = [1, 2; 3, 4] M3 = [10, 20; 30, 40]

and a matrix of indices

I = [1, 3; 1, 2]

I want to generate a new matrix M = [0.1, 20; 0.3, 4] by selecting the first entry from M1, second from M3, etc.

I can definitely do it in a nested loop, going through each entry and filling in the value, but I am sure there is a more efficient way.


What if M1, M2, M3 and M are all 3D matrices (RGB images)? Each entry of I tells us from which matrix we should take a 3-vector. Say, if I(1, 3) = 3, then we know entries indexed by (1, 3, :) of M should be M3(1, 3, :).

最满意答案

在不改变存储变量的方式的情况下,这样做的方法是使用蒙版。 如果你有几个矩阵,它正在做避免for循环的工作。 如果不经过cat函数或使用单元格,将无法完全进行矢量化。

M = zeros(size(M1)); Itmp = repmat(I==1,[1 1 size(M1,3)]); M(Itmp) = M1(Itmp); Itmp = repmat(I==2,[1 1 size(M1,3)]); M(Itmp) = M2(Itmp); Itmp = repmat(I==3,[1 1 size(M1,3)]); M(Itmp) = M3(Itmp);

A way of doing this, without changing the way you store your variable is to use masks. If you have a few matrices, it is doing the job avoiding a for loop. You won't be able to fully vectorize without going through the cat function, or using cells.

M = zeros(size(M1)); Itmp = repmat(I==1,[1 1 size(M1,3)]); M(Itmp) = M1(Itmp); Itmp = repmat(I==2,[1 1 size(M1,3)]); M(Itmp) = M2(Itmp); Itmp = repmat(I==3,[1 1 size(M1,3)]); M(Itmp) = M3(Itmp);

更多推荐

本文发布于:2023-07-15 18:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1117487.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩阵   索引   MATLAB   Select   indices

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!