我有一个矩阵A
和B
。我想把它们之间的平方和误差ss = sum(sum( (A-B).^2 ))
,但我只想这样做,如果NEITHER矩阵元素相同为零。现在,我按如下方式浏览每个矩阵:
for i = 1:N
for j = 1:M
if( A(i,j) == 0 )
B(i,j) = 0;
elseif( B(i,j) == 0 )
A(i,j) = 0;
end
end
end
然后取平方和。有没有办法对比较和重新分配值进行矢量化?
答案 0 :(得分:2)
如果您只是想要实现列出的代码所做的事情,但是以矢量化的方式,您可以使用这种方法 -
%// Create mask to set elements in both A and B to zeros
mask = A==0 | B==0
%// Set A and B to zeros at places where mask has TRUE values
A(mask) = 0
B(mask) = 0
如果可以考虑找到sum of squares errors after the listed code
的更大背景,你可以这样做 -
df = A - B;
df(A==0 | B==0) = 0;
ss_vectorized = sum(df(:).^2);
或者@carandraug评论说,您可以使用内置的sumsq
进行最后一步的平方和计算 -
ss_vectorized = sumsq(df(:));