How to set a default value for my custom function

I hope to create such custom function
function addnum(mat,n=numel(mat))
mat+n
I mean I try to add a number into the element of mtrix mat,but if I don't give a explicit value for n,I hope the n will be the number of the mtrix self.

 採用された回答

Stephen23
Stephen23 2017 年 7 月 17 日
編集済み: Stephen23 2017 年 7 月 17 日

5 投票

Unfortunately MATLAB does not (currently) allow defining default values in the function definition line itself (nor does it allow arguments to be specified by name, only by position). To define a default value you can use the input parser class (I find this slow and pointlessly complex), or simply use nargin like this:
function out = addnum(mat,n)
if nargin<2
n = 3;
end
out = mat+n;
end
For more multiple optional arguments you should consider using a structure or name-value pairs: see my FEX submission num2words for an example of this.

その他の回答 (2 件)

KSSV
KSSV 2017 年 7 月 17 日

0 投票

function addnum(mat)
n=numel(mat)
mat+n

4 件のコメント

Yode
Yode 2017 年 7 月 17 日
編集済み: Yode 2017 年 7 月 17 日
Thanks man,but I hope addnum(mat,3) works either,then every element will add 3. :)
KSSV
KSSV 2017 年 7 月 17 日
yes..
Yode
Yode 2017 年 7 月 17 日
@KSSV Sorry,that work for you ?
KSSV
KSSV 2017 年 7 月 17 日
function addnum(mat)
n=numel(mat)
mat+n
If you are using the above one....don't send any input just call it by addnum(mat), if you want logically select n then follow Stephen Cobeldick suggested.

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

Lee
Lee 2023 年 2 月 11 日

0 投票

This is the way to define default number in matlab
function addnum(mat,n)
arguments
mat
n=numel(mat)
end
mat+n
end
Be sure to list all arguments in order

カテゴリ

ヘルプ センター および File Exchange循环及条件语句 についてさらに検索

タグ

質問済み:

2017 年 7 月 17 日

回答済み:

Lee
2023 年 2 月 11 日

Community Treasure Hunt

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

Start Hunting!