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

1 次查看(过去 30 天)
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

采纳的回答

Guillaume
Guillaume 2014-9-20
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 个评论
Jessica Benidict
Jessica Benidict 2014-9-20
编辑:Jessica Benidict 2014-9-20
That code works perfectly if I have no input value for working_program however what about the other cases? I want a 3 by 4 matrix of random number to occur if i type in working_program(3,4) instead I am given
if true
working_program(3,4)
ans =
0.4125
0.4122
0.7758
end
Guillaume
Guillaume 2014-9-20
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Calendar 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by