matlab - Need help in using bsxfun -


i have 2 arrays in matlab:

a; % size(a) = [nx ny nz 3 3] b; % size(b) = [nx ny nz 3 1] 

in fact, in 3 dimensional domain, have 2 arrays defined each (i, j, k) obtained above-mentioned arrays a , b, respectively , sizes [3 3] , [3 1], respectively. let's sake of example, call these arrays m , n.

m; % size(m) = [3 3] n; % size(n) = [3 1] 

how can solve m\n each point of domain in vectorize fashion? used bsxfun not successful.

solution = bsxfun( @(a,b) a\b, a, b ); 

i think problem expansion of singleton elements , don't know how fix it.

i tried solutions, seems loop acutally fastest possibility in case.

a naive approach looks this:

%iterate c=zeros(size(b)); a=1:size(a,1)     b=1:size(a,2)         c=1:size(a,3)             c(a,b,c,:)=squeeze(a(a,b,c,:,:))\squeeze(b(a,b,c,:));         end     end end 

the squeeze expensive in computation time, because needs advanced indexing. swapping dimensions instead faster.

a=permute(a,[4,5,1,2,3]); b=permute(b,[4,1,2,3]); c2=zeros(size(b)); a=1:size(a,3)     b=1:size(a,4)         c=1:size(a,5)             c2(:,a,b,c)=(a(:,:,a,b,c))\(b(:,a,b,c));         end     end end c2=permute(c2,[2,3,4,1]); 

the second solution 5 times faster.

/update: found improved version. reshaping , using 1 large loop increases speed again. version suitable used parallel computing toolbox, in case own replace parfor , start workers.

a=permute(a,[4,5,1,2,3]); b=permute(b,[4,1,2,3]); %linearize , b better performance lina=reshape(a,[size(a,1),size(a,2),size(a,3)*size(a,4)*size(a,5)]); linb=reshape(b,[size(b,1),size(b,2)*size(b,3)*size(b,4)]); c3=zeros(size(linb)); a=1:size(lina,3)     c3(:,a)=(lina(:,:,a))\(linb(:,a)); end %undo linearization c3=reshape(c3,size(b)); %undo dimension swap c3=permute(c3,[2,3,4,1]); 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -