Passing individual elements of an array into a function
조회 수: 106 (최근 30일)
이전 댓글 표시
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.
댓글 수: 1
답변 (2개)
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.
댓글 수: 0
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!