joh*_*ech 2 matlab multidimensional-array matrix-indexing
我有一个3维矩阵,以及(行,列)对的列表.我想提取与那些位置中的元素相对应的二维矩阵,通过矩阵的深度投影.例如,假设,
>> a = rand(4, 3, 2)
a(:,:,1) =
0.5234 0.7057 0.0282
0.6173 0.2980 0.9041
0.7337 0.9380 0.9639
0.0591 0.8765 0.1693
a(:,:,2) =
0.8803 0.2094 0.5841
0.7151 0.9174 0.6203
0.7914 0.7674 0.6194
0.2009 0.2542 0.3600
>> rows = [1 4 2 1];
>> cols = [1 2 1 3];
Run Code Online (Sandbox Code Playgroud)
我想得到的是,
0.5234 0.8765 0.6173 0.0282
0.8803 0.2542 0.7151 0.5841
Run Code Online (Sandbox Code Playgroud)
也许有一些维度的排列.此外,尽管此示例在最后一个维度中具有通配符,但我也有其中第一个或第二个维度的情况.
我天真地尝试a(rows, cols, :)并获得了一个3d矩阵,其中对角线平面是我想要的.我还发现sub2ind,它将从a(:,:,1)飞机上提取所需的元素.我可以使用其中一个来达到我想要的效果,但我想知道是否有一个更缺乏规范,优雅或高效的方法?
这是我使用的解决方案,基于下面的答案,
sz = size(a);
subs = [repmat(rows, [1, sz(3)]);
repmat(cols, [1, sz(3)]);
repelem([1:sz(3)], length(rows))];
result = a(sub2ind(sz, subs(1,:), subs(2,:), subs(3,:)));
Run Code Online (Sandbox Code Playgroud)
sub2ind几乎是你必须用来将你的下标转换为线性索引(除了自己手动计算线性索引).可以执行类似下面将转换rows并cols为线性指数(在2D切片),然后将其附加一偏移(等于在2D切片元件的数量),以这些指标进行采样,第三的所有元素尺寸.
sz = size(a);
inds = sub2ind(sz(1:2), rows, cols);
inds = bsxfun(@plus, inds, (0:(sz(3)-1)).' * prod(sz(1:2)));
result = a(inds);
Run Code Online (Sandbox Code Playgroud)
并自己实际计算线性指数
inds = (cols - 1) * sz(1) + rows;
inds = bsxfun(@plus, inds, (0:(sz(3) - 1)).' * prod(sz(1:2)));
result = a(inds);
Run Code Online (Sandbox Code Playgroud)
另一个选择是置换初始矩阵以将第三维带到第一维,将其重新整形为二维矩阵,然后使用线性索引作为第二个下标
% Create a new temporary matrix
anew = reshape(permute(a, [3, 1, 2]), size(a, 3), []);
% Grab all rows (the 3rd dimension) and compute the columns to grab
result = anew(:, (cols - 1) * size(a, 1) + rows);
Run Code Online (Sandbox Code Playgroud)