call function with fewer parameters
Show older comments
gg(a)
function gg(a,b,c)
end
what happen if i call function with 1 parameter instead of 3
1 Comment
No need to explain this behaviour, I guess.
a = 2;
gg(a)
gg_error(a)
function result = gg(a,b,c)
result = a.^2;
end
function result = gg_error(a,b,c)
result = a.^2 + b.^2;
end
Accepted Answer
More Answers (1)
In MATLAB, it is not directly an error to call a function with fewer parameters than it is defined with.
Instead, at the time that you try to use one of the names defined as a parameter, if fewer parameters have been passed and you did not already assign to that variable, then you will get an error about not enough parameters.
aa = 123;
gg(aa)
function gg(a,b,c,d)
if nargin < 2
b = 456;
end
c = 789;
a
b
c
d
end
Here we do not pass in a value for b, but that is okay because we used nargin to detect the situation and assigned a default value for b.
Here we do not pass in a value for c, but that is okay because we ignored whatever c was passed in and always assigned a value to c before we tried to use it.
Here we do not pass in a value for d, and by the time we need d, we still have not assigned a value to d, so it is an error.
Categories
Find more on Variables 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!