Passing individual elements of an array into a function

조회 수: 136(최근 30일)
William Hewlett 2021년 1월 26일
편집: Stephen 2021년 1월 26일
Say I have a function 'myfun' that takes n inputs: i.e. myfun(x1, x2, ... xn).
I have an array 'arr' that has n elements: i.e. arr = [ y1, y2, ... yn ].
I want to pass in y1, y2 ... yn as the input to myfun without typing myfun( arr(1), arr(2), ... arr(n) ). Is there a compact way of doing this?
If I type in myfun( arr(1:end) ) for example, x1 = arr and x2 ... xn are left unassigned,
but I want x1 = arr(1) = y1, x2 = arr(2) = y2 ... xn = arr(n) = yn.

답변(2개)

Matt Gaidica 2021년 1월 26일
I don't think so, closest I can think of is using varargin. I think many people are going to ask why you need to use your design instead of passing a matrix itself into the function.
댓글 수: 1표시숨기기 없음
Walter Roberson 2021년 1월 26일
varargin will not help, not unless you code like
function myfun(varargin)
if nargin == 1
values = nargin{1};
else
values = [nargin{:}];
end
end
to allow you to pass either a single argument matrix or a list of values.

댓글을 달려면 로그인하십시오.

Walter Roberson 2021년 1월 26일
temp = num2cell(arr(1:end));
myfun(temp{:})
This situation is most common when the user has used matlabFunction to convert a symbolic function into a function handle. There is a completely different solution for that situation that avoids doing the splitting at all.
x = sym('x', [1 n]);
myfun = matlabFunction(YourSymbolicExpression, 'vars', {x});
This will tell matlabFunction to expect all of the input values to be packed into a single parameter, and to extract them from there as needed.
In this particular way of writing it, if the function is vectorizable, then the result will be vectorized with each column representing a different input. For example,
x = sym('x', [1 2]);
y = x(1)^2 + x(2);
myfun = matlabFunction(y, 'vars', {x});
would produce
myfun = @(in) in(:,1).^2 + in(:,2)
and you could
myfun([1 2; 3 4])
which would result in
[1^2+2; 3^2+4]
If you used 'vars', {x.'} then each row would correspond to a different variable and it would vectorize along the columns.

댓글을 달려면 로그인하십시오.

R2019b

Community Treasure Hunt

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

Start Hunting!