MATLAB: Enhancing a Function so that it can be called using the following syntax

narginrandom number generatorsyntax

HELP. I want to be able to call the below function using the following syntax
working_program
working_program(n)
working_program(n,m)
working_program(n,'method')
working_program(m,n,'method')
If a user inputs no values a single random number should be generated If a user inputs (n), the function should return a n x n square matrix If a user inputs (m,n), the function should return a m x n matrix* * * *
function y = working_program(n, method)
switch method
case 'NR' %parameters from Numerical Recipes book
a=1664525;
b=1013904223;
c=2^32;
case 'RANDU' %RANDU generator
a=65539;
b=0;
c=2^31;
otherwise
error('Invalid method')
end
seed=mod(a*etime(clock,[1993 6 30 8 15 0])+b,c);
y= zeros(n,1);
y(1)= seed;
for i=2:n
y(i)=mod(a*y(i-1)+b,c);
end
y=y/c; %normalizing so all values are between 0 and 1

Best Answer

You use nargin to check how many arguments were passed and ischar or isnumeric to test whether they're strings or numeric, e.g: (there are many ways to do this, you could also use varargin)
y = function working_program(n, arg1, method)
switch nargin
case 0
n=1; m=1; method = 'RANDU';
case 1
m=n; method = 'RANDU';
case 2
if ischar(arg1)
m=n; method = arg1;
else
m=arg1; method = 'RANDU';
end
case 3
m=arg1;
end
%the rest of your code
end