【问题标题】:Accessing a data matrix using indices stored at another matrix使用存储在另一个矩阵中的索引访问数据矩阵
【发布时间】:2019-06-27 23:27:36
【问题描述】:

在 matlab 中,我通常有一个大小为 NxMxLxK 的数据矩阵,我希望使用大小为 NxMxL 且值为 1..K 的索引矩阵沿特定维度(例如第四个维度)进行索引(假设都在此范围内) :

>>> size(Data)
ans =
     7    22    128    40
>>> size(Ind)
ans =
     7    22    128

我想要实现以下效果的不循环代码:

Result(i,j,k) = Data(i,j,k,Ind(i,j,k))

对于 i,j,k 范围内的所有值。

【问题讨论】:

  • 你能确定 Ind 的值在 1-40 之间吗?
  • 是的,太好了!但是你对 SO 有什么期待呢?请根据指南详细说明您的问题。
  • @Adiel:是的,我已经添加了这个假设。
  • 看我的回答

标签: matlab matrix indexing


【解决方案1】:

您可以向量化您的矩阵并使用sub2ind

% create indices that running on all of the options for the first three dimensions:
A = kron([1:7],ones(1,22*128));
B = repmat(kron([1:22],ones(1,128)),1,7);
C = repmat([1:128],1,7*22);

Result_vec = Data(sub2ind(size(Data),A,B,C,Ind(:)'));
Result = reshape(Result_vec,7,22,128);

【讨论】:

  • 这是专门针对 4-D 矩阵的,我是否更正了 3-D 矩阵的解决方案会更简单,使用 [A,B]=meshgrid(...)?
  • 听起来是这样。
  • 无论如何,输出矩阵中的一些向量。
猜你喜欢
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 2015-06-16
  • 2012-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-17
相关资源
最近更新 更多