2015-04-12 23 views
1

我有一個矩陣AB。我想把他們之間的平方誤差之和作爲ss = sum(sum((A-B).^2)),但我只想這樣做,如果任何矩陣元素都是相同的零。現在,我正在經歷如下每個矩陣:這個操作可以在Octave中矢量化嗎?

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 

然後再取其後的平方和。有沒有一種方法可以將比較和重新分配值進行矢量化?

回答

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(:)); 
+0

使用'sumsq(df(:))'而不是'sum(df(:))^ – carandraug

+0

@carandraug不錯,謝謝!不知道這個八度內置的!編輯。 – Divakar