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 个评论
Stephen23
2020-11-7
"You can create an array of function handles by collecting them into a cell or structure array."
回答(1 个)
Walter Roberson
2020-11-7
for i =1:5
S_i{i} = @(x) z(i)/3.*(p(i+1) -x)^3
end
6 个评论
Yancheng Wang
2020-11-7
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)
S{2}(3)
S{3}(3)
S{4}(3)
S{5}(3)
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
So far everything behaves exactly as expected.
Yancheng Wang
2020-11-7
编辑:Yancheng Wang
2020-11-7
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
metadata = functions(f);
metadata.workspace{1}
Even if we change n in the workspace, the remembered value in f will not change.
n = 3;
metadata2 = functions(f);
metadata2.workspace{1}
Yancheng Wang
2020-11-7
编辑:Yancheng Wang
2020-11-7
Walter Roberson
2020-11-8
S_i{i} = @(x) z(i)/3.*(p(i+1) -x).^3 %notice .^ instead of ^
类别
在 帮助中心 和 File Exchange 中查找有关 Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!