[英]Matlab: How to vectorize a nested loop over a 2D set of vectors
I have a function in the following form: 我有以下形式的函数:
function Out = DecideIfAPixelIsWithinAnEllipsoidalClass(pixel,means,VarianceCovarianceMatrix)
ellipsoid = (pixel-means)'*(VarianceCovarianceMatrix^(-1))*(pixel-means);
if ellipsoid <= 1
Out = 1;
else
Out = 0;
end
end
I am doing remote-sensing processes with matlab and I want to classify a LandSatTM images.This picture has 7 bands and is 2048*2048.So I stored them in 3 dimentinal 2048*2048*7 matrix.in this function means is a 7*1 matrix calculated earlier using the sample of the class in a function named ExtractStatisticalParameters and VarianceCovarianceMatrix is a 7*7 matrix in fact you see that: 我正在用matlab进行遥感过程,我想对LandSatTM图像进行分类,这张照片有7个波段,为2048 * 2048,所以我将它们存储在3个二维2048 * 2048 * 7矩阵中,此功能意味着一个7先前在名为ExtractStatisticalParameters和VarianceCovarianceMatrix的函数中使用该类的样本计算出的* 1矩阵实际上是一个7 * 7的矩阵,您会看到:
ellipsoid = (pixel-means)'*(VarianceCovarianceMatrix^(-1))*(pixel-means);
is the equation of an ellipsoid.My problem is that each time you can pass a single pixel(it is a 7*1 vector where each row is the value of the pixel in a seperated band) to this function so I need to write a loop like this: 我的问题是每次可以传递单个像素(它是7 * 1向量,其中每一行是分隔带中像素的值)时,我需要编写一个像这样循环:
for k1=1:2048
for k2=1:2048
pixel(:,1)=image(k1,k2,:);
Out = DecideIfAPixelIsWithinAnEllipsoidalClass(pixel,means,VarianceCovarianceMatrix);
end
end
and you know it will take alot of time and energy of the system.Can you suggest me a way to reduce the pressure applied on the systam? 而且您知道这将花费大量时间和精力。您能为我提供一种减轻系统压力的方法吗?
No need for loops! 无需循环!
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
After a (somewhat heated) debate in the comments below I add a correction made by Rody Oldenhuis : 经过下面的评论(有点激烈)辩论之后,我添加了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)) );
The key issue in this change is that Matlab's inv()
is poorly implemented and it is best to use mldivide
and mrdivide
(operators /
and \\
) instead. 此更改的关键问题是Matlab的
inv()
实现不佳, 最好改用mldivide
和mrdivide
(运算符/
和\\
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.