Passing individual elements of an array into a function

111 ビュー (過去 30 日間)
William Hewlett
William Hewlett 2021 年 1 月 26 日
編集済み: Stephen23 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 件)

Walter Roberson
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.

Matt Gaidica
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
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 ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by