how to not use all input arguments in the function because some of the arguments are fixed?
7 ビュー (過去 30 日間)
古いコメントを表示
how to not use all input arguments in the function because some of the arguments are fixed?
採用された回答
DGM
2022 年 2 月 16 日
編集済み: DGM
2022 年 2 月 16 日
If you're writing a function and want certain arguments to be optional (with internal defaults), read about varargin
From the scope of the function, varargin can be handled as a cell array. How you parse/validate its contents is up to your needs.
I generally assign all the parameters to their default values prior to parsing the inputs, overwriting the defaults as the user-defined values are collected from varargin.
3 件のコメント
DGM
2022 年 2 月 16 日
Unless area() is nested inside another function wherein B is defined, the above definition isn't available to it. It would either need to be explicitly passed to area(), or area() would need to internally define it such that it's a constant or a default for an optionally user-specified parameter.
As I doubt it really makes sense to have a rectangle area function that presumes the size of the rectangle, Steven's suggestion is probably more appropriate.
That said, I'll just offer this for sake of clarification anyway.
area(5,10)
area(5)
function [A] = area(varargin)
% A = area(height,{width})
% calculate the area of a rectangle
% if not specified, the width is assumed to be 20
B = 20; % default
narginchk(1,2);
switch nargin
case 1
h = varargin{1};
case 2
h = varargin{1};
B = varargin{2};
end
A = B*h;
end
その他の回答 (1 件)
Steven Lord
2022 年 2 月 16 日
編集済み: Steven Lord
2022 年 2 月 16 日
You can use an anonymous function "adapter".
f = @(in1, in2) max(in1, in2); % I could have used @max
% but I wanted to be explicit
f_2p5 = @(x) f(x, 2.5); % Call f with the first input specified by
% the user and the second fixed by me as 2.5
f_2p5(1:5)
f(1:5, 2.5)
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Argument Definitions についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!