matlab - 如何将向量(沿第四维)分配给预先指定的下标

标签 matlab matrix variable-assignment

我有一个 x、y、z 矩阵坐标矩阵,以及一个与这些坐标关联的时间序列相对应的行向量矩阵。例如

coordinates = [1 2 3; 57 89 22]; % Where the column 1 = x, column 2 = y, column 3 = z
timeseries = rand(2,200); % where each row corresponds to the timeseries of the coordinates in the same row in the coordinates matrix.

我想构建一个包含这些时间序列的 4D 矩阵。任何未分配的坐标都应默认为零向量。目前我这样做如下:

M = zeros(100,100,100,200); 
for ii = 1:size(coordinates,1)
    M(coordinates(ii,1),coordinates(ii,2),coordinates(ii,3),:) = timeseries(ii,:);
end

这行得通,但我想知道是否有一种(更具可读性/效率)的方法来一步编写 for 循环。我试过使用逻辑数组和索引,但它总是失败,因为我分配的是向量,而不是标量。

最佳答案

这是使用 sub2ind 的方法.我还没有计时:

sz = [100 100 100 200];
M = zeros(sz(1)*sz(2)*sz(3), sz(4));
ind = sub2ind(sz([1 2 3]), coordinates(:,1), coordinates(:,2), coordinates(:,3));
M(ind(:),:) = timeseries;
M = reshape(M, sz);

您可以通过手动计算代替 sub2ind 稍微提高速度:

sz = [100 100 100 200];
M = zeros(sz(1)*sz(2)*sz(3), sz(4));
ind = coordinates(:,1) + sz(1)*(coordinates(:,2)-1) + sz(1)*sz(2)*(coordinates(:,3)-1);
M(ind(:),:) = timeseries;
M = reshape(M, sz);

关于matlab - 如何将向量(沿第四维)分配给预先指定的下标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54221547/

相关文章:

matlab - 有没有使用Matlab计算Precision和Recall的函数?

matlab - `im2col`和 `col2im`的高效实现

r - 如何轻松地可视化矩阵?

Perl:还有比 $var = $_; 更好的东西吗?

c# - 引用问题: when are two objects equal?

c++ - 在 C++ 代码中调用 Matlab - 使用 engine.h 中的方法

matlab - 在 Simulink 中使用符号变量

matlab - 如何用多列显示一列矩阵

python - 从数据列表中创建矩阵列表

python - 调试时python中的locals()字典是只读的吗?