简体   繁体   中英

use of varargin in matlab

I have a function contains input arguments as var1 to var5 , I want to use varargin in order to user-defined input arguments, how can I assing var1 to var5 to input arguments? I tried, but this gives error as undeifned function or variable var1 . How if I want to skip var2 when calling a function? My code:

function  out= myFunc(varargin)
varargin{1} = var1;
varargin{2} = var2;
varargin{3} = var3;
varargin{4} = var4;
varargin{5} = var5;
%operations on var1,var2,var3,var4 and var5 like
var1 == 'variable1';
end

Put the variable you are assigning to on the left hand of the = sign, not the right.

You can also use the colon operator on a cell array to do multiple assignment via a comma-separated list, if you know you'll aways get at least that many arguments passed to this function.

[var1, var2, var3, var4, var5] = varargin{1:5};

If you know you'll have exactly five arguments, you can just use : when indexing in to the argument list.

[var1, var2, var3, var4, var5] = varargin{:};

And if you're uninterested in a particular input argument, you can either omit it from the list of indexes on the right hand side, or use ~ as a placeholder on the left hand side to discard it. Let's say you only care about inputs 1, 3, and 4, and want to toss inputs 2 and 5. You can do either of these.

[var1, var3, var4] = varargin{[1 3 4]};
[var1, ~, var3, var4, ~] = varargin{1:5};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM