Passing A Variable Number of Arguments into a Function

≯℡__Kan透↙ 提交于 2019-12-25 12:26:15

问题


In Matlab, I have a variable length cell of values:

C={A1,...,An}

How should I pass and distribute these values into a function able to receive a variable number of arguments?

f(A1,...,An)

Ultimately if not possible, how should I modify the beginning of this function for making this work?


回答1:


You need to convert the cell array into a comma-separated list via curly-brace indexing, that is, use C{:}.

Example with the reshape function:

>> C = {ones(3,4), 2, 2, 3};
>> y = reshape(C{:});
>> size(y) % check
ans =
     2     2     3



回答2:


This is exactly what 'varargin' does for you. Read in multiple variables, e.g. f(a,b,c), and store them in a cell-array.

Then you could go for one of these 'quick and dirty' processing methods:

function asdf(varargin)
  yourarguments=[varargin{:}]; % if all numerical
  yourargumentscontain=contains(varargin,'asdf'); %if strings contained
  all_processed_args=cellfun(@(x) whateveryouwant_function(x), varargin); %for older versions of matlab
end

For more here's documentation: https://ch.mathworks.com/help/matlab/matlab_prog/parse-function-inputs.html



来源:https://stackoverflow.com/questions/47735705/passing-a-variable-number-of-arguments-into-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!