在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);更多推荐
发布评论