Error using function handles in for loop
1 次查看(过去 30 天)
显示 更早的评论
I have a function, pi_t, which is defined using a function handle but also is a function i in the for loop. When I try to incorporate my function handle inside the for loop it gives an error for pi_t saying "Nonscalar arrays of function handles are not allowed; use cell arrays instead." What I want to do is to have Np amount of pi_t values with the function handle but with the dpi(i) value correctly substituted in the equation for pi_t. Any ideas how to effectively use a function handle in a for loop?
a_pi20 = 1.50;
b_pi20 = 2.25;
c_pi20 = 3;
dist_pi20 = makedist('Triangular', a_pi20, b_pi20, c_pi20);
pi08 = 8.50;
Np = 1000;
for i = 1:Np
pi20 = random(dist_pi20);
dpi(i) = (pi20 - pi08)/(12*pi08);
pi_t(i) = @(x)abs(-dpi(i)*x(1)*pi08 - pi08);
end
0 个评论
回答(2 个)
Walter Roberson
2017-4-26
pi_t{i} = @(x)abs(-dpi(i)*x(1)*pi08 - pi08);
and to call it, you would need something like
pi_t{17}(37.8)
2 个评论
Walter Roberson
2017-4-26
fzero( pi_t{17}, x0 )
"When I type in pi_t(1) after using your suggestion it gives me @(x)(-dpi(i)*x(1)*pi08-pi08)"
p{1} would give that, and it is fine. It has "captured" the value that dpi(i) had at the time the function handle was created. It will not display as @(x)(-0.06*x(1)*pi08-pi08) but it will execute that way. You can use
temp = functions(pi_t{1});
temp2 = temp.workspace{1};
temp2.dpi
temp2.i
to see that it has copied dpi and i; those are what it will use at execution time.
KSSV
2017-4-26
You can follow with out suing function as below. (Note that x is not defined, I have taken some random value).
a_pi20 = 1.50;
b_pi20 = 2.25;
c_pi20 = 3;
dist_pi20 = makedist('Triangular', a_pi20, b_pi20, c_pi20);
pi08 = 8.50;
Np = 1000;
pi_t = zeros(1,Np) ;
dpi = zeros(1,Np) ;
x = rand ;
for i = 1:Np
pi20 = random(dist_pi20);
dpi(i) = (pi20 - pi08)/(12*pi08);
pi_t(i) = abs(-dpi(i)*x*pi08 - pi08);
end
If you want to go by function. You have to define the function first and then call the function in the loop. An example code given below would help you to understand.
f = @(x) x+2 ;
y = zeros(1,10) ;
for i = 1:10
y(i) = f(i) ;
end
Also note that, your entire code can be vectorised with out using loop. As a beginner it is always good to know loops and then vectorize it.
5 个评论
KSSV
2017-4-27
You have not mentioned x so I have taken it random. If you define what is x it can be included in the code.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!