Matlab - Singleton extension for more than two inputs

I have a function that takes more than two variables

eg.

testFunction = @(x1, x2, x3, x4) x1.*x2.*x3.*x4; testFunction2 = @(x1, x2, x3) sin(x1.*x2.^x3); 

Is there a function available as bsxfun that allows a one-color extension for functions with more than two inputs?

bsxfun example

 binaryTestFunction = @(x1, x2) x1.*x2; x1 = 9*eye(10); x2 = 3*ones(10,1); A = bsxfun(binaryTestFunction , x1 , x2); 

Extends the singleton dimension in the x2 vector.
bsxfun faster than repmat, and also very iterative, and so I want to know if a uniform extension of my testFunction .

+7
vectorization matlab bsxfun
source share
2 answers

You can define your own class that allows bsxfun to be used automatically:

 classdef bdouble < double %BDOUBLE double with automatic broadcasting enabled methods function obj=bdouble(data) obj = obj@double (data); end function r=plus(x,y) r=bsxfun(@plus,x,y); end function r=minus(x,y) r=bsxfun(@minus,x,y); end function r=power(x,y) r=bsxfun(@power,x,y); end function r=times(x,y) r=bsxfun(@times,x,y); end function r=rdivide(x,y) r=rdivide(@rdivide,x,y); end function r=ldivide(x,y) r=ldivide(@ldivide,x,y); end end end 

Using:

  testFunction(bdouble([1:3]),bdouble([1:4]'),bdouble(cat(3,1,1)),bdouble(1)) 

If you prefer the bsxfun syntax, you can put this on top:

 function varargout=nbsxfun(fun,varargin) varargout=cell(1:nargout); for idx=1:numel(varargin) if isa(varargin{idx},'double') varargin{idx}=bdouble(varargin{idx}); end end varargout{1:max(nargout,1)}=fun(varargin{:}); end 

Example:

 n=nbsxfun(testFunction,[1:3],[1:4]',cat(3,1,1),4) 
+2
source share

Socket functions only:

 testFunction = @(x1, x2, x3, x4) bsxfun(@times, bsxfun(@times, bsxfun(@times, x1, x2), x3), x4); testFunction2 = @(x1, x2, x3) sin(bsxfun(@power, bsxfun(@times, x1, x2), x3); 

Please note that you must implement bsxfun inside a function and not rely on the user calling the function using bsxfun, so interaction with the function is independent.

Note also that there is a slight speed limit between using bsxfun when direct elementary operations could be used.

There was a file in the file exchange that overrides the operators of the array, so bsxfun is automatically used for all operators, but I cannot remember its name. I used this for a while, but then you risk that users do not realize that this is implemented.

+1
source share

All Articles