function handle array Problem
Show older comments
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)
Accepted Answer
More Answers (1)
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.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!