从代码来看,您所做的是对于ttable 的每一行,您希望使用abs(formula(i,:)) 访问的索引并将这些位置中的每一个设置为-1*formula(i,:)。
注意到@Divakar 的聪明点,我将假设每一行都有唯一的绝对 值。换句话说,每一行都不应该有可以连续有a 或-a 的实例,其中a 是从1 到size(formula,2) 的任意数字。原因是因为在您计算 abs(formula(i,:)) 时,-a 和 a 将映射到同一列。这将发生冲突并允许覆盖到同一个条目中(感谢@Divakar!)
我们可以对formula 的每一行,将这些位置转换为列主索引以访问ttable。之后,将-1*formula 的对应值赋值给ttable。换句话说:
%// Find those columns that should be accessed
columnIndices = reshape(abs(formula).', 1, []);
%// For each column we are accessing, find the corresponding row
rowIndices = reshape(repmat(1:size(formula,2), size(formula, 1), 1), 1, []);
%// Find the column major indices we need to access overall
indices = sub2ind(size(formula), rowIndices, columnIndices);
%// Take those indices that we have computed above, and map them
%// to those columns we found earlier
ttable(indices) = -1*formula.';
这是我创建的一个小测试。这也是基于我之前所做的唯一绝对值的相同假设:
formula = [1 2 -3 4; 4 -2 3 1; 3 2 4 -1; -4 1 2 3];
ttable = NaN(length(formula),max(max(abs(formula))));
formula =
1 2 -3 4
4 -2 3 1
3 2 4 -1
-4 1 2 3
ttable =
NaN NaN NaN NaN
NaN NaN NaN NaN
NaN NaN NaN NaN
NaN NaN NaN NaN
使用您的方法,我们得到:
for i = 1:length(formula)
ttable(i,abs(formula(i,:))) = -1*formula(i,:);
end
ttable =
-1 -2 3 -4
-1 2 -3 -4
1 -2 -3 -4
-1 -2 -3 4
使用我的方法,我们得到:
columnIndices = reshape(abs(formula).', 1, []);
rowIndices = reshape(repmat(1:size(formula,2), size(formula, 1), 1), 1, []);
indices = sub2ind(size(formula), rowIndices, columnIndices);
ttable(indices) = -1*formula.';
ttable =
-1 -2 3 -4
-1 2 -3 -4
1 -2 -3 -4
-1 -2 -3 4
如果您的矩阵很小,那么这样做而不是 for 循环的计算开销可能会更大,因此效率会很低。但是,如果您的矩阵更大,那么此代码可能会更快。无论哪种方式,我认为您的 for 循环方法仍然很好。 JIT 应该为for 循环启动。如果您在对使用for 循环作为算法之一的算法进行一些时序测试时查看这篇文章,那么for 循环是最快的算法之一。在这里查看:MATLAB: Subtracting matrix subsets by specific rows