我正在编写一个 MATLAB 函数来将数据读出到一个 n 维数组(可变维度大小)中。我需要能够访问 Matrix 中的特定点(例如写入或读取它),但我不知道提前指定多少索引。
目前我有一个 current_point
向量,我迭代它来指定每个索引,还有一个 max_points
向量,它指定数组的大小。因此,例如,如果我想要一个大小为 1000×15×3 的 3 维数组,max_points = [1000 15 3]
,并且 current_point
从[1, 1, 1]
到 [1000, 15, 3]
([1, 1, 1]
-> [ 1000, 1, 1]
-> [1, 2, 1]
-> [1000, 2, 1]
->...)。我想做的是将 current_point
作为索引提供给矩阵,如下所示:
output_matrix(current_point) = val
但显然 output_matrix([1 2 3]) = val
只会设置 outputmatrix(1:3) = 30
。我不能只使用虚拟变量,因为有时矩阵需要 3 个索引,有时需要 4 个,有时需要 2 个,等等,所以可变长度的向量才是我真正需要的。有没有一种简单的方法可以使用向量作为索引中的点?
最佳答案
使用函数sub2ind
创建一个 linear index是此问题的典型解决方案,如本 closely-related question 所示.你也可以compute a linear index yourself而不是调用 sub2ind
。
但是,您的情况可能比我链接到的其他问题中的情况更简单。如果您只使用 current_point
向量索引单个点(即它只是 n 维矩阵中下标的 n 元素向量),那么您可以使用一个简单的解决方案,使用函数 num2cell
将 current_point
转换为下标元胞数组并用它来创建一个 comma-separated list指数。例如:
current_point = [1 2 3 ...]; % A 1-by-n array of subscripts
subCell = num2cell(current_point); % A 1-by-n cell array of subscripts
output_matrix(subCell{:}) = val; % Update the matrix point
subCell{:}
操作创建等效于键入 subCell{1}, subCell{2}, ...
,这等效于键入 current_point(1), current_point(2), ...
.
关于matlab - 使用向量作为矩阵的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5904488/