20.08.2015 Views

MATLAB array manipulation tips and tricks

MATLAB array manipulation tips and tricks - Home - Online.no

MATLAB array manipulation tips and tricks - Home - Online.no

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 11. MORE COMPLICATED ARITHMETIC OPERATIONS 37which is computed more efficiently with the following code which does some inlining of functions(mean <strong>and</strong> cov) <strong>and</strong> vectorizationnx = size(X, 1);ny = size(Y, 1);% size of set in X% size of set in Ym = sum(X, 1)/nx; % centroid (mean)Xc = X - m(ones(nx,1),:);% distance to centroid of XC = (Xc’ * Xc)/(nx - 1); % variance matrixYc = Y - m(ones(ny,1),:);% distance to centroid of Xd = sum(Yc/C.*Yc, 2)); % Mahalanobis distancesIn the complex case, the last line has to be written asd = real(sum(Yc/C.*conj(Yc), 2)); % Mahalanobis distancesThe call to conj is to make sure it also works for the complex case. The call to real is to remove“numerical noise”.The Statistics Toolbox contains the function mahal for calculating the Mahalanobis distances,but mahal computes the distances by doing an orthogonal-triangular (QR) decomposition of thematrix C. The code above returns the same as d = mahal(Y, X).Special case when both matrices are identical If Y <strong>and</strong> X are identical in the code above, thecode may be simplified somewhat. The for-loop solution becomesn = size(X, 1);% size of set in Xm = mean(X);C = cov(X);d = zeros(n, 1);for j = 1:nd(j) = (Y(j,:) - m) / C * (Y(j,:) - m)’;endwhich is computed more efficiently withn = size(x, 1);m = sum(x, 1)/n; % centroid (mean)Xc = x - m(ones(n,1),:);% distance to centroid of XC = (Xc’ * Xc)/(n - 1); % variance matrixd = sum(Xc/C.*Xc, 2); % Mahalanobis distancesAgain, to make it work in the complex case, the last line must be written asd = real(sum(Xc/C.*conj(Xc), 2));% Mahalanobis distances

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!