Question:

Setting default values for Matlab function input parameters?

by  |  earlier

0 LIKES UnLike

How do you set default values in Matlab for the input parameters for a created function

 Tags:

   Report

1 ANSWERS


  1. There is not any very clean way but most used is checking how many input arguments have been given. Number of given input arguments can be accessed using 'nargin' (for number of outputs 'nargout').

    Now you could write

    function [out1 out2 out3] = myfun(in1, in2, in3)

    if nargin < 3

    in3 = 3;

    end

    if nargin < 2

    in2 = 2;

    end

    if nargin == 0

    in1 = 1;

    end

    out1 = 2;

    out2 = 4;

    out3 = 3;

    if nargout < 3

    out1 = in1*in2;

    end

    return

    You can also make much more complicated tricks if you use 'varargin':

    function out = myfun(in1,varargin)

    Varargin will 'catch' input arguments after argument 'in1' is assigned, this means that you could use function call:

    myfun(1,2,3,4,5,6,7,8,9) and it would not generate error.

    Now in1 will get value '1' and varargin will be cell array with length of 8 {2,3,4,5,6,7,8}, nargin would still be 9. I hope I didn't make things too complicated :) Just check nargin and assign rest of the variables accordingly.

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.