How to set up matlab ODE function for cos(theta) - matlab

I want to create an ODE file for the equation d^2theta/dt^2 - cos(theta) = 0
I have this:
function dYdt = osciODE(t,Y,~,theta)
dYdt = zeros(2,1);
dYdt (1) = Y(2);
dYdt (2) = -cos(theta1);
But I don't think this is right as dYdt (1) would be for d^2x/dt^2
Can I replace it with theta like this?

One way to solve this ODE is :
[t,y] = ode23(#osciode,[0 20],[2; 0]);
plot(t,y(:,1),'-o',t,y(:,2),'-o')
title('Solution osciode with ODE23 : y1=y ; y2=dy/dt');
grid on
xlabel('t');ylabel('y');
legend('y_1','y_2')
%%
function dydt = osciode(t,y)
dydt = [y(2); cos(y(1))];
end
y is theta

Related

what is wrong in Second Order Differential Equation?

My code is
I am trying to plot a graph of second order differential equation
clc;
funcprot(0);
function dx = f(t,x)
dx(1) = x(2);
dx(2) = sin(2 * t);
endfunction
t = 0: 0.1 : 4 * %pi;
y = ode ([0,-1/2],0,t,f);
plot2d(t',[y(1,:)',y(2,:)']);
xlabel('t'); ylabel('y and derivative');
xtitle('Plot of solution of 2nd order ODE')
Just transpose the initial condition:
clc;
funcprot(0);
function dx = f(t,x)
dx(1) = x(2);
dx(2) = sin(2 * t);
endfunction
t = 0: 0.1 : 4 * %pi;
y = ode ([0,-1/2]',0,t,f);
plot2d(t',[y(1,:)',y(2,:)']);
xlabel('t'); ylabel('y and derivative');
xtitle('Plot of solution of 2nd order ODE')

MATLAB fminunc stopped becaise it cannot decrease the objective formula?

I am trying to using fminunc to obtain the optimal theta in logistic regression, however I keep getting that:
fminunc stopped because it cannot decrease the objective function
along the current search direction.
Searching online, I found that this is usually the result of a gradient error which I am implementing in logistic_costFunction.m. I re-checked my work but I cannot spot the root cause.
I am not sure how to solve this issue, any help would be appreciated.
Here is my code:
clear all; close all; clc;
%% Plotting data
x1 = linspace(0,3,50);
mqtrue = 5;
cqtrue = 30;
dat1 = mqtrue*x1+5*randn(1,50);
x2 = linspace(7,10,50);
dat2 = mqtrue*x2 + (cqtrue + 5*randn(1,50));
x = [x1 x2]'; % X
subplot(2,2,1);
dat = [dat1 dat2]'; % Y
scatter(x1, dat1); hold on;
scatter(x2, dat2, '*'); hold on;
classdata = (dat>40);
%% Compute Cost and Gradient
% Setup the data matrix appropriately, and add ones for the intercept term
[m, n] = size(x);
% Add intercept term to x and X_test
x = [ones(m, 1) x];
% Initialize fitting parameters
initial_theta = zeros(n + 1, 1);
% Compute and display initial cost and gradient
[cost, grad] = logistic_costFunction(initial_theta, x, dat);
fprintf('Cost at initial theta (zeros): %f\n', cost);
fprintf('Gradient at initial theta (zeros): \n');
fprintf(' %f \n', grad);
%% ============= Part 3: Optimizing using fminunc =============
% In this exercise, you will use a built-in function (fminunc) to find the
% optimal parameters theta.
% Set options for fminunc
options = optimset('GradObj', 'on', 'MaxIter', 400);
% Run fminunc to obtain the optimal theta
% This function will return theta and the cost
[theta, cost] = ...
fminunc(#(t)(logistic_costFunction(t, x, dat)), initial_theta, options);
logistic_costFunction.m
function [J, grad] = logistic_costFunction(theta, X, y)
% Initialize some useful values
m = length(y); % number of training examples
grad = zeros(size(theta));
H = sigmoid(X*theta);
T = y.*log(H) + (1 - y).*log(1 - H);
J = -1/m*sum(T);
% ====================Compute grad==================
for i = 1 : m
grad = grad + (H(i) - y(i)) * X(i,:)';
end
grad = 1/m*grad;
end
sigmoid.m
function g = sigmoid(z)
% Computes thes sigmoid of z
g = zeros(size(z));
g = 1 ./ (1 + (1 ./ exp(z)));
end

MatLab ODE start/stop conditions for ode15i

I was searching for ways to terminate MATLAB ode when it meets a particular condition. I found the answer in this topic MatLab ODE start/stop conditions, where the use of 'events' was discussed. However this applies to ode45 and when I attempted to use 'events' with ode15i, it simply didn't worked and MATLAB is showing error.
I am trying to learn this with simple example and solved a simple system of differential equations as given below.
dx/dt = 5x + 3y; dy/dt = x + 7y; I solved them using ode45 and tried to do the same with ode15i, but it doesn't work. Given below are my codes.
With ode45
function start_stop_test_ode45
y0 = [5;1];
tv = linspace(0,2,100);
options = odeset('Events',#events);
f = #(t,y) [5*y(1) + 3*y(2);y(1) + 7*y(2)];
[t,Y] = ode45(f,tv,y0,options);
xNI = Y(:,1);
yNI = Y(:,2);
xCF = 3*exp(4*t) + 2*exp(8*t);
yCF = -1*exp(4*t) + 2*exp(8*t);
% Here we plot all the graphs
figure(1)
plot(t,xNI,'--k',t,xCF,'r','Linewidth',1.75)
xlabel('t (s)')
ylabel('x')
legend('Numerical Solution','Closed Form Solution')
figure(2)
plot(t,yNI,'--k',t,yCF,'r','Linewidth',1.75)
xlabel('t (s)')
ylabel('y')
legend('Numerical SOlution','Closed Form Solution')
% Here we solve plot the variation of x with y
figure(3)
plot(xNI,yNI,'k','Linewidth',2);
end
function [value,isterminal,direction] = events(t,y)
value = [y(1) - 7782;y(2) - 8863]; % Detect y = 7356
isterminal = [1;1];
direction = [0;0];
end
With ode15i
function start_stop_test_ode15i
clc;clear all
t0 = 0;
y0 = [5;1];
Fxdy0 = [1;1];
Fxdyp0 = [0;0];
yp0 = [28;12];
tRange = [0 2];
options = odeset('Events',#events);
[y0,yp0] = decic(#ode15ifun,t0,y0,Fxdy0,yp0,Fxdyp0);
sol = ode15i(#ode15ifun,tRange,y0,yp0,options);
tv = linspace(0,2,100);
sv = deval(sol,tv);
sv = sv';
t = tv;
xNI = sv(:,1);
yNI = sv(:,2);
xCF = 3*exp(4*t) + 2*exp(8*t);
yCF = -1*exp(4*t) + 2*exp(8*t);
% Here we plot all the graphs
figure(4)
plot(t,xNI,'--k',t,xCF,'r','Linewidth',1.75)
xlabel('t (s)')
ylabel('x')
legend('Numerical Solution','Closed Form Solution')
figure(5)
plot(t,yNI,'--k',t,yCF,'r','Linewidth',1.75)
xlabel('t (s)')
ylabel('y')
legend('Numerical SOlution','Closed Form Solution')
% Here we solve plot the variation of x with y
figure(6)
plot(xNI,yNI,'k','Linewidth',2);
end
function [value,isterminal,direction] = events(t,y)
value = [y(1) - 7782;y(2) - 8863]; % Detect y = 7356
isterminal = [1;1];
direction = [0;0];
end
Where the ode15ifun is
function res = ode15ifun(t,y,yp)
%UNTITLED3 Summary of this function goes here
% Detailed explanation goes here
res1 = yp(1) - 5*y(1)- 3*y(2);
res2 = yp(2) - y(1) - 7*y(2);
res = [res1;res2];
end
ode45 is working fine but while using ode15i I am getting error message. Can anyone help as to how to do the same with ode15i?
Thank you very much
(In Response to TroyHaskin) I am adding an image file of the error message for your reference.

Solving 2nd order differential equation with boundary condition z(inf) = 0

How can I solve a 2nd order differential equation with boundary condition like z(inf)?
2(x+0.1)·z'' + 2.355·z' - 0.71·z = 0
z(0) = 1
z(inf) = 0
z'(0) = -4.805
I can't understand where the boundary value z(inf) is to be used in ode45() function.
I used in the following condition [z(0) z'(0) z(inf)], but this does not give accurate output.
function [T, Y]=test()
% some random x function
x = #(t) t;
t=[0 :.01 :7];
% integrate numerically
[T, Y] = ode45(#linearized, t, [1 -4.805 0]);
% plot the result
plot(T, Y(:,1))
% linearized ode
function dy = linearized(t,y)
dy = zeros(3,1);
dy(1) = y(2);
dy(2) = y(3);
dy(3) = (-2.355*y(2)+0.71*y(1))/((2*x(t))+0.2);
end
end
please help me to solve this differential equation.
You seem to have a fairly advanced problem on your hands, but very limited knowledge of MATLAB and/or ODE theory. I'm happy to explain more if you want, but that should be in chat (I'll invite you) or via personal e-mail (my last name AT the most popular mail service from Google DOT com)
Now that you've clarified a few things and explained the whole problem, things are a bit more clear and I was able to come up with a reasonable solution. I think the following is at least in the general direction of what you'd need to do:
function [tSpan, Y2, Y3] = test
%%# Parameters
%# Time parameters
tMax = 1e3;
tSpan = 0 : 0.01 : 7;
%# Initial values
y02 = [1 -4.805]; %# second-order ODE
y03 = [0 0 4.8403]; %# third-order ODE
%# Optimization options
opts = optimset(...
'display', 'off',...
'TolFun' , 1e-5,...
'TolX' , 1e-5);
%%# Main procedure
%# Find X so that z2(t,X) -> 0 for t -> inf
sol2 = fminsearch(#obj2, 0.9879680932400429, opts);
%# Plug this solution into the original
%# NOTE: we need dense output, which is done via deval()
Z = ode45(#(t,y) linearized2(t,y,sol2), [0 tMax], y02);
%# plot the result
Y2 = deval(Z,tSpan,1);
plot(tSpan, Y2, 'b');
%# Find X so that z3(t,X) -> 1 for t -> inf
sol3 = fminsearch(#obj3, 1.215435887288112, opts);
%# Plug this solution into the original
[~, Y3] = ode45(#(t,y) linearized3(t,y,sol3), tSpan, y03);
%# plot the result
hold on, plot(tSpan, Y3(:,1), 'r');
%# Finish plots
legend('Second order ODE', 'Third order ODE')
xlabel('T [s]')
ylabel('Function value [-]');
%%# Helper functions
%# Function to optimize X for the second-order ODE
function val = obj2(X)
[~, y] = ode45(#(t,y) linearized2(t,y,X), [0 tMax], y02);
val = abs(y(end,1));
end
%# linearized second-order ODE with parameter X
function dy = linearized2(t,y,X)
dy = [
y(2)
(-2.355*y(2) + 0.71*y(1))/2/(X*t + 0.1)
];
end
%# Function to optimize X for the third-order ODE
function val = obj3(X3)
[~, y] = ode45(#(t,y) linearized3(t,y,X3), [0 tMax], y03);
val = abs(y(end,2) - 1);
end
%# linearized third-order ODE with parameters X and Z
function dy = linearized3(t,y,X)
zt = deval(Z, t, 1);
dy = [
y(2)
y(3)
(-1 -0.1*zt + y(2) -2.5*y(3))/2/(X*t + 0.1)
];
end
end
As in my comment above, I think you're confusing a couple of things. I suspect this is what is requested:
function [T,Y] = test
tMax = 1e3;
function val = obj(X)
[~, y] = ode45(#(t,y) linearized(t,y,X), [0 tMax], [1 -4.805]);
val = abs(y(end,1));
end
% linearized ode with parameter X
function dy = linearized(t,y,X)
dy = [
y(2)
(-2.355*y(2) + 0.71*y(1))/2/(X*t + 0.1)
];
end
% Find X so that z(t,X) -> 0 for t -> inf
sol = fminsearch(#obj, 0.9879);
% Plug this ssolution into the original
[T, Y] = ode45(#(t,y) linearized(t,y,sol), [0 tMax], [1 -4.805]);
% plot the result
plot(T, Y(:,1));
end
but I can't get it to converge anymore for tMax beyond 1000 seconds. You may be running into the limits of ode45 capabilities w.r.t. accuracy (switch to ode113), or your initial value is not accurate enough, etc.

Solving this differential equation with matlab?

This would be it :
y'(t)=y(t)/t-t^2/y^2*t
y(1)=1
i have tried:
function hazi3b()
[T,Y] = ode45( #bfugveny, [1 12], 1);
plot(T, Y, 'gx')
end
and:
function dy=bfugveny(t,y)
dy = y(t)/t - t^2/(y^2*t);
end
You don't need to write y(t) in your formula.
The y passed into your oracle is already a guess for y-evaluated-at-time-t.
So try
dy = y/t - t^2/(y^2*t);