Defining function handles in a for loop

Hello everyone,
I have trying to define a series of function handles that are very similar. They only differ by their constant coefficients. They general idea is that I want to define functions s1 to s5 such that
for i =1:5
S_i = @(x) z(i)/3.*(p(i+1) -x)^3
end
where each s takes on their coefficeints from vectors z and p, as shown. But it seems like Matlab does not allow an array of function handles. What should I do?
Thanks a lot guys!

답변 (1개)

Walter Roberson
Walter Roberson 2020년 11월 7일

0 개 추천

for i =1:5
S_i{i} = @(x) z(i)/3.*(p(i+1) -x)^3
end

댓글 수: 6

Yancheng Wang
Yancheng Wang 2020년 11월 7일
I tried this but then every cell has the exact same content--an expression in terms of i. It does not get iterated.
Lets try it with some random data:
z = rand(1,5);
p = rand(1,6);
for i = 1:5
S{i} = @(x) z(i)/3.*(p(i+1) -x)^3;
end
Checking:
S{1}(3)
ans = -1.1499
S{2}(3)
ans = -2.1649
S{3}(3)
ans = -3.9047
S{4}(3)
ans = -0.4100
S{5}(3)
ans = -1.1882
They don't look the same to me. Lets check one of them, say the fifth one:
z(5)/3.*(p(5+1) -3)^3
ans = -1.1882
So far everything behaves exactly as expected.
Yancheng Wang
Yancheng Wang 2020년 11월 7일
편집: Yancheng Wang 2020년 11월 7일
This is odd. So in the workspace they appear the same, but somehow they are indeed different as shown by output. If you could do a "whos" command on any cell, you would get exacly the same thing, which is the original expression containing the i. So, in this case, how would I graph these different functions? Matlab would allow me to.
Anonymous functions "remember" certain values in their bodies. You can check this using the functions function (which as its documentation page states should not be used programmatically, just for debugging.)
n = 2;
f = @(x) x.^n
f = function_handle with value:
@(x)x.^n
metadata = functions(f);
metadata.workspace{1}
ans = struct with fields:
n: 2
Even if we change n in the workspace, the remembered value in f will not change.
n = 3;
metadata2 = functions(f);
metadata2.workspace{1}
ans = struct with fields:
n: 2
Yancheng Wang
Yancheng Wang 2020년 11월 7일
편집: Yancheng Wang 2020년 11월 7일
Thank you! I did not know this and it helps!
So, as I defined the functions as above, when I try to graph them, matlab indicates that these are "array inputs" and should be "properly vectorized". Do you know what happened/what I should do to graph these functions?
Thanks again
S_i{i} = @(x) z(i)/3.*(p(i+1) -x).^3 %notice .^ instead of ^

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

카테고리

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

제품

릴리스

R2020a

질문:

2020년 11월 7일

댓글:

2020년 11월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by