Substitute variables in function handle

Hello,
I have two implementations.
  1. Create functions based on the parameter
  2. Pass this functions to another function and evaluate them there
I'm creating functions like this:
for i=1:n/2-1
funk{i} = @(x)2*x(i)-2+400*x(i)^3-400*x(i)*x(i+1);
end
I want this to create multiple functions (depends on n) with i to be superset by a number, but WITHOUT being solved right away as i want to hand it over to another function in which this should get solved.
How can I achieve this?
Thanks in advance

답변 (1개)

Walter Roberson
Walter Roberson 2022년 1월 24일

0 개 추천

What you have already done should work.
Although all of the function handles will look the same, they would have captured different values of i
For example,
for i = 1 : 2
funk{i} = @(x)2*x(i)-2+400*x(i)^3-400*x(i)*x(i+1);
end
ws1 = functions(funk{1}).workspace{1}
ws1 = struct with fields:
i: 1
ws2 = functions(funk{2}).workspace{1}
ws2 = struct with fields:
i: 2
Notice how the information embedded within the function handles funk{1} and funk{2} is different -- they have different embedded i values.

댓글 수: 2

So I can simply pass this to another function like:
for i = 1 : 2
funk{i} = @(x)2*x(i)-2+400*x(i)^3-400*x(i)*x(i+1);
end
function test(fun)
test(funk)
This returns an error that Array indices must be positive integers or logical values in my implementation of the calling function.
Torsten
Torsten 2022년 1월 24일
편집: Torsten 2022년 1월 24일
x = [1 2 3 4 5 6];
for i = 1 : 2
funk{i} = @(x)2*x(i)-2+400*x(i)^3-400*x(i)*x(i+1);
end
test(funk,x)
function test(fun,x)
fun{1}(x)
fun{2}(x)
end

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

카테고리

도움말 센터File Exchange에서 MATLAB에 대해 자세히 알아보기

제품

릴리스

R2021b

질문:

2022년 1월 24일

편집:

2022년 1월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by