function handle array Problem
조회 수: 3 (최근 30일)
이전 댓글 표시
Hi
The following code is a short expample of my real code. I want to compute iterativly U and V. And at the end i have a intergral where i want to divide the V by the U of the last iteration and then integrate that over the variable a.
How can i do this?
Thank you?
m = [1,2];
U(3) = @(a) a + 2;
V(3) = @(a) a - 2;
for j = 2:-1:1
a_i(j) = @(a) sqrt(a.^2 + 1i * m(j));
U{j} = @(a) + a_i(j) .* V{j+1};
V{j} = @(a) - a_i(j) .* U{j+1};
end
result = integral(V{1}(a) ./ U{1}(a), 0, 1000)
채택된 답변
Torsten
2023년 3월 23일
result = integral(@fun,0,1000,'ArrayValued',1)
function value = fun(a)
m = [1,2];
U(3) = a + 2;
V(3) = a - 2;
for j = 2:-1:1
a_i = sqrt(a^2 + 1i * m(j));
U(j) = a_i * V(j+1);
V(j) = a_i * U(j+1);
end
value = V(1)/U(1);
end
댓글 수: 3
Torsten
2023년 3월 23일
편집: Torsten
2023년 3월 23일
And if i use other variables (constants defined at the begin of the program) in the for loop, how can i pass them to the function?
As usual:
constant1 = 1;
constant2 = pi;
constant3 = exp(1);
result = integral(@(a)fun(a,constant1,constant2,constant3),0,1000,'ArrayValued',1)
function value = fun(a,constant1,constant2,constant3)
...
end
Or use a structure:
params.constant1 = 1;
params.constant2 = pi;
params.constant3 = exp(1);
result = integral(@(a)fun(a,params),0,1000,'ArrayValued',1)
function value = fun(a,params)
constant1 = params.constant1;
constant2 = params.constant2;
constant3 = params.constant3;
...
end
추가 답변 (1개)
Steven Lord
2023년 3월 23일
MATLAB no longer allows non-scalar arrays of function handles; I think the last release in which that was supported was release R13SP1 (MATLAB 6.5.1) or R13SP2 (MATLAB 6.5.2) back in 2003 though I could be wrong. I'm fairly certain it started at least issuing warnings if not throwing errors when we introduced anonymous functions in release R14 in 2004.
You can make a cell array of function handles like you did on this line (commented out so I can run code later in the answer):
% U{j} = @(a) + a_i(j) .* V{j+1};
but this doesn't do what you think it does. The + operator in this function handle does not add a_i(j).*V{j+1} to the function handle stored in either U{j} or U{j-1}. It is the unary plus operator. In addition, this will error when evaluated. You can't multiply a number by a function handle. You could multiply the result of evaluating a function handle by a number.
f = @(x) sin(x);
gWorks = @(x) 2.*f(x); % 2 times the result of evaluating f works
gDoesNotWork = @(x) 2.*f; % 2 times f does not work
[gWorks(1:5); 2*sin(1:5)]
gDoesNotWork(1:5)
What's the mathematical equation you're trying to integrate? It may be more straightforward to write a function in a file and integrate that function rather than trying to iteratively assemble a tower of anonymous functions.
참고 항목
카테고리
Help Center 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!