Using bsxfun with one-color extension with three dimension matrices

I use bsxfunto flatten operations with monotonous expansion between dimension matrices:

MS: (nms, nls)
KS: (nks, nls)

The operation is the sum of the absolute differences between each value MS(m,l)c min 1:nmsand lin 1:nls, and each KS(k,l)with kin 1:nks.

I achieve this through code:

[~, nls] = size(MS);
MS = reshape(MS',1,nls,[]);
R = sum(abs(bsxfun(@minus,MS,KS)));

Rhas a size (nls, nms).

I want to generalize this operation to a list of samples, so the new sizes will be:

MS: (nxs, nls, nms)
KS: (nxs, nls, nks)

This can be easily achieved with a for loop, which executes the first part of the code for each 2-dimensional matrix, but I suspect that performance can be much better by generalizing the previous code by adding a new dimension.

R has size: (nxs, nls, nms)

MS 4 . bsxfun?

+4
1

:

% generate small dummy data
nxs = 2;
nls = 3;
nms = 4;
nks = 5;
MS = rand(nxs, nls, nms);
KS = rand(nxs, nls, nks);

R = sum(abs(bsxfun(@minus,MS,permute(KS,[1,2,4,3]))),4)

[2,3,4], .. [nxs,nls,nms]. [k1,k2,k3]

R(k1,k2,k3) == sum_k abs(MS(k1,k2,k3) - KS(k1,k2,k))

,

R(2,1,3)

ans =

   1.255765020150647

>> sum(abs(MS(2,1,3)-KS(2,1,:)))

ans =

   1.255765020150647

, permute: permute(KS,[1,2,4,3]) [nxs,nls,1,nks], MS [nxs,nls,nms] [nxs,nls,nms,1]: MATLAB - . , bsxfun [nxs,nls,nms,1] [nxs,nls,1,nks], , [nxs,nls,nms,nks]. 4 .


, permute . , . , , (- ). :

% generate larger dummy data
nxs = 20;
nls = 30;
nms = 40;
nks = 500;
MS = rand(nxs, nls, nms);
KS = rand(nxs, nls, nks);

MS2 = permute(MS,[4 3 2 1]);
KS2 = permute(KS,[3 4 2 1]);
R3 = permute(squeeze(sum(abs(bsxfun(@minus,MS2,KS2)),1)),[3 2 1]);

, , nks . , . , , .

Runtimes : 0.07028 , 0,051162 ( 5). , , .

+6

Source: https://habr.com/ru/post/1624184/


All Articles