How to use my numeric array results as input values for an ODE?

So I have the following code:
n = 10 ;
result = zeros(n,5 );
for k=1:n ;
A0=1;P0=29;g=rand;p=rand;B=rand ;
result(k,:) = [A0,P0,g,p,B ];
end;
Which produces a 10x5 numeric array as the result.
And I'd like to use my results from there as the input values to solve this equation ten times:
tspan=[1 7];
[t,x] = ode45(@(t,x) [-g*x(1) + p*x(1); -x(1)*x(2)+ B*x(2)], tspan, [A0 P0]);
Is this possible?
Thanks in advance!

 Accepted Answer

Try this:
n = 10 ;
result = zeros(n,5 );
for k=1:n ;
A0=1;P0=29;g=rand;p=rand;B=rand ;
result(k,:) = [A0,P0,g,p,B ];
end
for k = 1:size(result,1)
tspan=linspace(0,7,50);
ODE = @(t,x,g,p,B) [-g*x(1) + p*x(1); -x(1)*x(2)+ B*x(2)];
[t,x(:,:,k)] = ode45(@(t,x) ODE(t,x,result(k,3),result(k,4),result(k,5)), tspan, [result(k,1) result(k,2)]);
end
It saves the output to a 3D matrix, as previously.

4 Comments

Thank you, that is incredibly helpful!
I just have one follow up question: once I've completed this, is there any way for me to plot my x values against my t values? Can I convert the 3D matrix to 2D (bc actually previously when I solved this OD it would spit out a 2D matrix, column 1 being solved x(1), column 2 being solved x(2)) or access those x values some way?
My pleasure!
It’s likely easiest to do it in a looop:
figure
hold all
for k = 1:size(x,3)
plot(t, x(:,:,k))
end
hold off
grid
Although you may want to plot the two values of ‘x’ separately using subplot to see the details:
figure
subplot(2,1,1)
hold all
for k = 1:size(x,3)
plot(t, x(:,1,k))
end
title('x_1')
grid
subplot(2,1,2)
hold all
for k = 1:size(x,3)
plot(t, x(:,2,k))
end
title('x_2')
grid
hold off
That is perfect, thank you so much!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!