how does a function invoke the inputs?

1 次查看(过去 30 天)
function [result] = test02(type,a,b,c,d)
%This function is used to test what will happen if only part of the inputs
%are needed to get the result.
switch type
case '1'
result=a+b;
case '2'
result=a+b+c+d;
otherwise
warning('Unexpected input type. Please check the input.')
end
end
I wonder how Matlab function tacitly 'uses' the inputs, so I wrote the function above and type the piece of codes below in the command line to see what if only part of the inputs are given. Unexpectedly, no error came up (Personally 'c' and 'd' are not essential to get the result for case '1'). Could anyone explain the reason why the function still works when only part of the inputs (type, a, b) are given? What's the mechanism of calling the inputs in a Matlab function?
type= '1';
a=1; b=2; c=3; d=4;
[result] = test02(type,a,b)

采纳的回答

Stephen23
Stephen23 2020-5-6
编辑:Stephen23 2020-5-6
  1. MATLAB's function input and output arguments are entirely positional. Their names are irrelevant.
  2. When calling a function, you need to provide the inputs that are used in the code that actually runs, e.g. if only the 3rd input is used in the code that runs then the 3rd input must be provided.
  3. ...but because of rule 1., this means you also also need to provide the 1st and 2nd inpust as well, although their values will be completely ignored because the code that runs does not use them.
  4. Unused inputs cannot be left "blank". Usually an empty array is used.

更多回答(1 个)

KSSV
KSSV 2020-5-6
It is because, your type = '1' needs only two inputs a,b ..
You try using type = '2' with only two inputs..it will throw error. For the type = '1' case, it needs only two inputs a, b nd you have provided them so there is no error.
  2 个评论
Shuangfeng Jiang
Shuangfeng Jiang 2020-5-6
Thx for answering. But the function is defined with 5 inputs, can we call the function with the no.inputs less than 5?
The example below would describe my confusion better.
function [result] = test03(type,a,b,c,d)
% case 1 was modified
switch type
case '1'
result=a+c;
case '2'
result=a+b+c+d;
otherwise
warning('Unexpected input type. Please check the input.')
end
end
For the modified function above, if I've only got 'a' and 'c' ('b' ,'d' are unknown), and case = '1', what should I type in the command line? May I left 'b' blank like below?
type= '1';
a=1; c=3;
[result] = test02(type,a, ,c)
Rik
Rik 2020-5-6
You can put in anything you want, because your function is going to ignore the actual contents of the variable. Usually people use an empty array [] to show that an input is ignored.
type= '1';
a=1; c=3;
result = test02(type,a,[],c)

请先登录,再进行评论。

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by