0

Possible Duplicate:
Default Arguments in Matlab

I have two functions in Matlab, test1 and test2, as shown below.

function [C,D] = test1(A,B)

A = 50;
B = 20;

C = A + B;
D = A - B;

end

and

function test2

C = 1000;
D = 500;

[A,B] = test1(C,D);

display(A)
display(B)

end

Now what I would like to do is have set default values for A and B in function test1 but also be able to pass into function test1 different values from another function like function test2. So by default have A and B set to 50 and 20 in function test1, but with function test2 be able to replace them with 1000 and 500, and obtain the equivalent C and D result (in the case of 1000 and 500, get a result of 1500 and 500 for C and D respectively)

How can I do this? Any help would be greatly appreciated. Thanks

Community
  • 1
  • 1
thomashs87
  • 59
  • 2
  • 4

2 Answers2

5

You can use Matlab's varargin for that purpose, e.g.

function [C,D] = test1(varargin)

A = 50;
B = 20;
if nargin > 0
  A = varargin{1};
end
if nargin > 1
  B = varargin{2};
end

C = A + B;
D = A - B;

end
3lectrologos
  • 9,469
  • 4
  • 39
  • 46
1

Several ways to do this

Check for the presence of the input:

if(~exist('A'))
 A = default;
end

Note the use of exist('A') rather than exist(A) - if A doesn't exist by virtue of not being passed, then this will throw an error.

Alternatively

if(nargin < 2)
 B = default_b;
end
if (nargin == 0)
 A = default_a;
end

Both of these methods are somewhat messy, and if you have many inputs you want to be optional, then you can use a matlab class inputParser

doc inputParser

for more details, I don't describe it here because it is very comprehensive (and maybe overkill for simple cases)

user1207217
  • 547
  • 1
  • 4
  • 15
  • The exist method was my first thought as well, but then how would you make the function call? I don't think this works unless you evaluate it every time before you call the function. – Dennis Jaheruddin Jan 15 '13 at 13:36
  • @Dennis `function testfun(testvar, varargin) if(exist('testvar')) disp('moo') end sprintf('%f\n', nargin)` `>> testfun ans = 0.000000 >> testfun(1) moo ans = 1.000000` – user1207217 Jan 18 '13 at 19:15