Default argument expression with multiple outputs

1 回表示 (過去 30 日間)
Scott
Scott 2023 年 8 月 21 日
コメント済み: Scott 2023 年 8 月 22 日
How do I get the correct output into the default argument if a function used in an expression has more than one output? E.g.
arguments
opts.input2 (1,1) double = function_with_multiple_outputs(function_inputs)
end
Where [output1, output2, etc] = function_with_multiple_outputs(function_inputs) and function_inputs are constants or previously defined arguments. I only want, e.g. opts.input2 to be output2 from function_with_multiple_outputs.

採用された回答

Steven Lord
Steven Lord 2023 年 8 月 22 日
Write a local function that calls function_with_multiple_outputs with multiple outputs then returns only the one you want to use for the default value. Call that local function instead of function_with_multiple_outputs in the arguments block.
  5 件のコメント
Stephen23
Stephen23 2023 年 8 月 22 日
"I don't see how this can work because if you declare a variable it is considered an argument"
It works for me, exactly as Steven Lord explained:
mytest(1,3)
ans = 4
function out = mytest(x,y,opts)
arguments
x
y
opts.input2 (1,1) double = localfun(x,y)
end
out = opts.input2;
end
function out = localfun(varargin)
[~,out] = function_with_multiple_outputs(varargin{:});
end
function [A,B] = function_with_multiple_outputs(X,Y)
A = NaN;
B = X+Y;
end
Scott
Scott 2023 年 8 月 22 日
Very good! Thank you.

サインインしてコメントする。

その他の回答 (2 件)

dpb
dpb 2023 年 8 月 22 日
Multiple output arguments must be unique variable names; just define the default for the specific name and it will refer to the one in that position.
  2 件のコメント
Walter Roberson
Walter Roberson 2023 年 8 月 22 日
No, you can have, for example,
[out{1:3}] = unique(randi(9, 1, 50))
out = 1×3 cell array
{[1 2 3 4 5 6 7 8 9]} {9×1 double} {50×1 double}
Scott
Scott 2023 年 8 月 22 日
I do not see this working because the outputs can have any name (different from the ones in the function declaration); it is the position that matters.

サインインしてコメントする。


Walter Roberson
Walter Roberson 2023 年 8 月 22 日
In MATLAB, there is no (useful) way to assign multiple outputs of a function to a single location, and there is no (useful) way to select a particular output from a command .
What would be legal generally in MATLAB (but not necessarily in an argument block) is
[opts.input2, opts.input2] = function_with_two_outputs();
This would assign the first output to opts.input2 and then assign the second output on top of opts.input2 .
  1 件のコメント
Stephen23
Stephen23 2023 年 8 月 22 日
"This would assign the first output to opts.input2 and then assign the second output on top of opts.input2 ."
Only if OPTS is scalar (or is implicitly created by that allocation).

サインインしてコメントする。

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by