フィルターのクリア

Finding out the size of x (so how many xi we have) in a function handle

7 ビュー (過去 30 日間)
Daniela Würmseer
Daniela Würmseer 2022 年 3 月 3 日
コメント済み: Daniela Würmseer 2022 年 3 月 4 日
Hello, if i have fore example the following function
f1 = @(x) x(1)^2+x(2)^2;
can we somehow find out the "size" of x? So with size of x i mean how many x Variables we have so in this example 2: x=(x(1),x(2))
f1 = @(x) x(1)^2+x(2)^2+x(2)+x(3);
And in this example the size of x would be three.
Thank you.

採用された回答

Matt J
Matt J 2022 年 3 月 3 日
One possibility,
f1 = @(x) x(1)^2+x(2)^2+x(2)+x(3);
str = extractBetween( func2str(f1),'x(',')');
dimension=max(str2double(str))
dimension = 3
  1 件のコメント
Daniela Würmseer
Daniela Würmseer 2022 年 3 月 4 日
Thanks to all.
This is a quiete clever way to do it.

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

その他の回答 (3 件)

Steven Lord
Steven Lord 2022 年 3 月 3 日
If you're doing this so you can dynamically generate the body of f that computes the sum of the squares of the elements of the input, you don't need to.
f = @(x) sum(x.^2);
f([1 2])
ans = 5
f([3 4 5])
ans = 50
f([6 7 8 9])
ans = 230
If you wanted f to have multiple inputs:
g = @(varargin) sum([varargin{:}].^2)
g = function_handle with value:
@(varargin)sum([varargin{:}].^2)
g(1, 2)
ans = 5
g(3, 4, 5)
ans = 50
g(6, 7, 8, 9)
ans = 230

Matt J
Matt J 2022 年 3 月 3 日
No, not from the function handle itself. Note that your f1 and f2 work for vectors of any length>3, e.g.,
f1 = @(x) x(1)^2+x(2)^2;
f1(1:5)
ans = 5
f1(rand(1,7))
ans = 0.0223
so f1 does cannot know the size of the vector you're giving it.

David Hill
David Hill 2022 年 3 月 3 日
g=@(x)f1(x);
g([1 2 3])
g([1 5])
function y=f1(x)
if length(x)==2
y=x(1)^2+x(2)^2;
elseif length(x)==3
y=x(1)^2+x(2)^2+x(2)+x(3);
end
end

カテゴリ

Help Center および File ExchangeFunctions についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by