[英]Matlab: How to vectorize a nested loop over a 2D set of vectors
我有以下形式的函數:
function Out = DecideIfAPixelIsWithinAnEllipsoidalClass(pixel,means,VarianceCovarianceMatrix)
ellipsoid = (pixel-means)'*(VarianceCovarianceMatrix^(-1))*(pixel-means);
if ellipsoid <= 1
Out = 1;
else
Out = 0;
end
end
我正在用matlab進行遙感過程,我想對LandSatTM圖像進行分類,這張照片有7個波段,為2048 * 2048,所以我將它們存儲在3個二維2048 * 2048 * 7矩陣中,此功能意味着一個7先前在名為ExtractStatisticalParameters和VarianceCovarianceMatrix的函數中使用該類的樣本計算出的* 1矩陣實際上是一個7 * 7的矩陣,您會看到:
ellipsoid = (pixel-means)'*(VarianceCovarianceMatrix^(-1))*(pixel-means);
我的問題是每次可以傳遞單個像素(它是7 * 1向量,其中每一行是分隔帶中像素的值)時,我需要編寫一個像這樣循環:
for k1=1:2048
for k2=1:2048
pixel(:,1)=image(k1,k2,:);
Out = DecideIfAPixelIsWithinAnEllipsoidalClass(pixel,means,VarianceCovarianceMatrix);
end
end
而且您知道這將花費大量時間和精力。您能為我提供一種減輕系統壓力的方法嗎?
無需循環!
pMinusMean = bsxfun( @minus, reshape( image, [], 7 ), means' ); %//' subtract means from all pixes
iCv = inv( arianceCovarianceMatrix );
ell = sum( (pMinusMean * iCv ) .* pminusMean, 2 ); % note the .* the second time!
Out = reshape( ell <= 1, size(image(:,:,1)) ); % out is 2048-by-2048 logical image
經過下面的評論(有點激烈)辯論之后,我添加了Rody Oldenhuis做出的更正 :
pMinusMean = bsxfun( @minus, reshape( image, [], 7 ), means' ); %//' subtract means from all pixes
ell = sum( (pMinusMean / varianceCovarianceMatrix ) .* pminusMean, 2 ); % note the .* the second time!
Out = reshape( ell <= 1, size(image(:,:,1)) );
此更改的關鍵問題是Matlab的inv()
實現不佳, 最好改用mldivide
和mrdivide
(運算符/
和\\
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.