Jack_111
Jack_111

Reputation: 891

writing function using varargin and varargout

I have this function and I want to use varargin and varargout for all the inputs and the outputs and I don't know exactly how to do it.

Any suggestions? This is my function:

function [Output0,Output1] = myfunction(p0,p1,normal0,normal1,c0,c1)

t0 = sqrt((c0^2)/((normal0(1)^2) + (normal0(2)^2) + (normal0(3)^2)));
Output0= p0 + normal0*t0;

t1 = sqrt((c1^2)/((normal1(1)^2) + (normal1(2)^2) + (normal1(3)^2)));
Output1= p1 + normal1*t1;

Thanks in advance

Upvotes: 1

Views: 335

Answers (1)

Dan
Dan

Reputation: 45752

I don't think this is an appropriate case for varargin or even for nargin. This is a case for vectorizing your function.

OK so lets say you have these inputs: xo, yo, zo, x1, y1, z1 (all scalar), normal0 (1x3), normal1 (1x3) and c0 and c1 both scalar.

Lets see if we can vectorize your function to calculate all the outputs in one shot. So first we'll rearrange your data:

P = [x0, x1;
     y0, y1
     z0, z1];

N = [normal0;
     normal1]'; %better here to just make normal0 a (3x1) so no need to transpose

C = [c0, c1]

now lets look at how you got your first output:

t0 = sqrt((c0^2)/((normal0(1)^2) + (normal0(2)^2) + (normal0(3)^2)));
Output0= p0 + normal0*t0;

this can be simplified to

p0 + normal0 * sqrt(c0^2/sum(normal0.^2))

which can be generalized to

P + bsxfun(@times,N,sqrt(bsxfun(@rdivide,C.^2,sum(N.^2))))

So now you get any number of outputs in one shot! In one line too!

Just a quick explanation of where bsxfun came into it. So in your original calcs you sometimes multiply or add a scalar to a vector. Matlab allows this but it doesn't allow the higher dimensional case of say adding a vector to a 2D matrix. bsxfun does this for us. so where I have bsxfun(@times, N, B) above, it just takes the 3x1 B vector and does an elementwise multiplication (@times is the function handle to .*) of B on each column of the 3x2 N. But here it's fine for N to be 3xX i.e. have any number of columns i.e. any number of inputs.

Upvotes: 3

Related Questions