call function with fewer parameters
46 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
gg(a)
function gg(a,b,c)
end
what happen if i call function with 1 parameter instead of 3
1 comentario
Respuesta aceptada
Voss
el 24 de Oct. de 2023
"what happen if i call function with 1 parameter instead of 3"
The answer depends on what the function does with the parameters.
I've defined two functions below: gg_1, which takes three inputs and uses the first one only, and gg_all, which takes three inputs and uses them all. Whether I call gg_1 with one input or two or three, it runs without error, but when I call gg_all with fewer than three inputs, an error occurs at the first line of code that tries to access an input that was not given. See below.
You can use nargin to determine how many inputs were given (and write code to handle different possible number of inputs).
a = 1;
b = 2;
c = 3;
gg_1(a,b,c) % three inputs given; only the first is used; ok
gg_1(a) % one input given, which is used; ok
gg_all(a,b,c) % three inputs given; all are used; ok
gg_all(a) % one input given; expected three; error
% this function uses the first parameter only
function gg_1(a,b,c)
disp(a);
end
% this function uses all three parameters
function gg_all(a,b,c)
disp(a); % error would happen here if a were not given
disp(b); % error happens here when a is given but b is not given
disp(c); % error would happen here if a and b were given but not c
end
0 comentarios
Más respuestas (1)
Walter Roberson
el 24 de Oct. de 2023
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.
0 comentarios
Ver también
Categorías
Más información sobre Whos en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!