Matlab: How to vectorize a nested loop over a 2D set of vectors

后端 未结 1 1603
悲&欢浪女
悲&欢浪女 2020-12-21 18:33

I have a function in the following form:

function Out = DecideIfAPixelIsWithinAnEllipsoidalClass(pixel,means,VarianceCovarianceMatrix)  
   ellipsoid = (pi         


        
相关标签:
1条回答
  • 2020-12-21 19:02

    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
    

    Update:

    After a (somewhat heated) debate in the comments below I add a correction made by 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.

    0 讨论(0)
提交回复
热议问题