MATLAB Answers

Is it possible to have an array of function handles?

5 views (last 30 days)
I am trying to make an array of function handles so that, for example, I can create a function that looks like this:
[x,y]= RK4system(f ,xspan, y0, N);
Instead of this:
[x,y]= RK4system(y1prime,y2prime ,xspan, y0, N);
Therefore, I want a function handle 'f' that contains y1prime and y2prime, where :
y1prime = @(x,y1,y2) y2;
y2prime = @(x,y1,y2) -2*x^2*y1 - 3*x*y2;
Here is the actual function if you need it:
function [x,y]= RK4system(y1prime, y2prime ,xspan, y0, N)
x(1) = xspan(1);
xf = xspan(2);
y1(1) = y0(1);
y2(1) = y0(2);
h=xf/N;
for i=1:N
x(i+1) = x(i)+h;
k1y1 = y1prime(x(i),y1(i),y2(i));
k1y2 = y2prime(x(i),y1(i),y2(i));
k2y1 = y1prime(x(i)+h/2, y1(i)+h/2*k1y1, y2(i)+h/2*k1y2);
k2y2 = y2prime(x(i)+h/2, y1(i)+h/2*k1y1, y2(i)+h/2*k1y2);
k3y1 = y1prime(x(i)+h/2, y1(i)+h/2*k2y1, y2(i)+h/2*k2y2);
k3y2 = y2prime(x(i)+h/2, y1(i)+h/2*k2y1, y2(i)+h/2*k2y2);
k4y1 = y1prime(x(i)+h, y1(i)+h*k3y1, y2(i)+h*k3y2);
k4y2 = y2prime(x(i)+h, y1(i)+h*k3y1, y2(i)+h*k3y2);
y1(i+1) = y1(i)+h/6*(k1y1 + 2*k2y1 + 2*k3y1 + k4y1);
y2(i+1) = y2(i)+h/6*(k1y2 + 2*k2y2 + 2*k3y2 + k4y2);
end
x=x';
y1=y1';
y2=y2';
y=[y1 y2];
end
When calling the function:
N = 4;
y1prime = @(x,y1,y2) y2;
y2prime = @(x,y1,y2) -2*x^2*y1 - 3*x*y2;
xspan = [0 0.4];
y0 = [3 1];
[x,y]= RK4system(y1prime,y2prime ,xspan, y0, N);
[x y]

  0 Comments

Sign in to comment.

Accepted Answer

per isakson
per isakson on 1 Jun 2020
The short answer is no. However, it's possible to store function handles in a cell array.
f = cell(2,1);
f{1} = y1prime;
f{2} = y2prime;

More Answers (0)