MATLAB: Nargin

homeworknargin

Can anyone please tell me what if the nargin function is doing? I've been trying to learn how to use matlab on my own. //thanx
function [m_hat,s2hat ] = yatzy(n)
for m = 1:n
value = tillsfem(5);
throws(m) = value;
end
m_hat = mean(throws);
s2hat = var(throws);
throw_max = max(throws);
p = [];
A = [0 1/6 1/36 1/216 1/1296;
0 5/6 10/36 15/216 25/1296;
0 0 25/36 80/216 250/1296;
0 0 0 120/216 900/1296;
0 0 0 0 120/1296];
e1 = [1 0 0 0 0]';
e5 = [0 0 0 0 1]';
p = zeros(throw_max, n);
for m = 1:throw_max
pm = e1'*A^m*e5;
p(m) = pm;
end
if nargin < 2
k = 1:throw_max;
p = p*n;
else
p = p*n*throw_max/k;
end
figure(1); clf;
hist(throws,k);
hold on
stem(1:throw_max,p,'r')
title('number of throws to get 5 equal dice')
legend('Numerical','Analytical')
xlabel('Number of throws')
ylabel('Frequency')
hold off
fprintf(['Expected number of throws to get: %4.2f '...
'(analytical)\n' ...
' %4.2f '...
'(numerical)\n' ...
'Expected variance: %4.2f '...
'(analytical)\n' ...
' %4.2f '...
'(numerical)\n'], ...
191283/17248, m_hat, 12125651655/297493504, s2hat);
I just need help with explaining
if nargin < 2
k = 1:throw_max;
p = p*n;
else
p = p*n*throw_max/k;

Best Answer

nargin means "number of arguments in". In the above code it looks pretty useless:
if nargin < 2
%do stuff
end
nargin in this case can only be 0 or 1, since yatzy(n) only allows for one input argument, (n), or no input arguments, yatzy. If you call yatzy with two input arguments, e.g.
yatzy(4,5)
It will error out with something along the lines of "Error using yatzy, more input arguments than expected"
Now as for future reference, since you're learning: nargin is typically used for error checking and so you can have optional arguments, e.g:
let's write a program f that takes one or two input arguments with the 2nd being optional:
function out = f(x,y);
if nargin==0
%user called >>f
error('Not enough input arguments, 1 is required');
elseif nargin==1
%user called f(x)
y = pi;
end %if neither, user called f(x,y)
Here we've made sure the person enters at least one argument, x, if they entered a second one great! if not, the second one, y, = pi.
Good luck!
Related Question