Enhancing a Function so that it can be called using the following syntax
1 view (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Guillaume
on 20 Sep 2014
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
2 Comments
Guillaume
on 20 Sep 2014
I just showed you how to write a function that accept a variable numbers of input of different types. I assumed that the rest of your program would behave properly given the values n and m, e.g:
%the rest of the program
%... do wathever you want with method
y = rand(n, m); %generate a n x m matrix of random numbers
More Answers (0)
See Also
Categories
Find more on Calendar in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!