How to assign default values to function inputs

91 ビュー (過去 30 日間)
K E
K E 2016 年 11 月 30 日
コメント済み: K E 2016 年 12 月 2 日
I have a function with some required inputs,
heatContent = function(swRadiation, lwRadiation)
If the user passes in [] for any of the inputs, I would like to substitute default values (swRadiation=100 or lwRadiation=50). Also if the user only passes in 1 input, I would substitute in lwradiation=50 for the second input. I believe I can use inputparser to do this, but the following gives an error (Undefined function or variable 'lwRadiation'). I could write a long chain of if/elseif statements but suspect there is a more compact way.
p = inputparser;
addOptional(p,'swRadation',50);
addOptional(p,'lwRadiation',100);

採用された回答

Jan
Jan 2016 年 11 月 30 日
編集済み: Jan 2016 年 11 月 30 日
How should the code decide which input was given, when you provide one input only?
The inputParser is a powerful tool. But hard coding is not complicated here:
function heatContent = function(swRadiation, lwRadiation)
switch nargin
case 0
swRadiation = [];
lwRadiation = [];
case 1
lwRadiation = [];
case 2
otherwise
error('2 inputs are accepted.')
end
if isempty(swRadiation)
swRadiation = 50;
end
if isempty(lwRadiation)
lwRadiation = 100;
end
...
The inputParser expects name-value pairs to identify the inputs. This allows to change the order of the inputs and you can provide the 2nd input only without ambiguities.
  1 件のコメント
K E
K E 2016 年 12 月 2 日
It is good to know that there is not in fact a shortcut via inputparser, and that if statements are a fine approach.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by