solving differential equation using matlab - matlab

I have a question and just need you to tell me the steps I have to do.
I have an equation with boundary conditions.the question is how can I find f(x)?
I don't want to use the predefined Matlab.Please just show me the steps I need to solve this problem.
Thanks...

Simply you can use symbolic math toolbox in MATLAB:
syms f(x) % Define symbolic function
F = dsolve(diff(f,2) + diff(f,1) + 200*f == 0);
% Find C1 and C2 constants
syms C1 C2 L
BC_eq(1) = subs(F, x, 0) - 0;
BC_eq(2) = subs(F, x, L) - 100;
C_val = solve(BC_eq, [C1, C2]);
% Substitude C' values in F
F_final = subs(F, {C1, C2}, {C_val.C1, C_val.C2})

Related

Matlab solving ODEs can not understand this function description

I have stumbled upon this matlab code that solves this ODE
y'''(t) + a y(t) = -b y''(t) + u(t)
but I am confused by the ode_system function definition, specifically by the y(2) y(3) part. I would greatly appreciate if someone can shed some light
y(2) y(3) part in the ode_system function confuses me and how it contributes to overaal solution
% Define the parameters a and b
a = 1;
b = 2;
% Define the time horizon [0,1]
time_horizon = [0, 1];
% Define the initial conditions for y, y', and y''
initials = [0; 0; 0];
% Define the function handle for the input function u(t)
%sin(t) is a common example of a time-varying function.
% You can change the definition of u to any other function of time,
% such as a constant, a step function, or a more complex function, depending on your needs
u = #(t) sin(t);
% Define the function handle for the system of ODEs
odefunction = #(t, y) ode_system(t, y, a, b, u);
% Solve the ODEs using ode45
[t, y] = ode45(odefunction, time_horizon, initials);
% Plot the solution
plot(t, y(:,1), '-', 'LineWidth', 2);
xlabel('t');
ylabel('y');
function dydt = ode_system(t, y, a, b, u)
%Define the system of ODEs
dydt = [y(2); y(3); -b*y(3) + u(t) - a*y(1)];
end
This is more of a maths question than a Matlab one.
We would like to rewrite our ODE equation so that there is a single time derivative on the left-hand side and no derivatives on the right.
Currently we have:
y'''(t)+ay(t)=-by''(t)+u(t)
By letting z = y' and x = z' (= y''), we can rewrite this as:
x'(t)+a y(t)=-b x(t)+u(t)
So now we have 3 equations in the form:
y' = z
z' = x
x' = -b * x + u - a *y
We can also think of this as a vector equation where v = (y, z, x).
The right-hand side would then be,
v(1)' = v(2)
v(2)' = v(3)
v(3)' = -b * v(3) + u - a * v(1)
which is what you have in the question.

How to numerically solve a system with two matrices in Matlab?

I'm trying to numerically find the solution to A*cos x +B*sin x = C where A and B are two known square matrices of the same size (for example 100x100), and C is a known vector (100x1).
Without the second term (i.e. with a single matrix), I will use Jacobi or Gauss-Seidel to solve this problem and get x but here, I don't see how to proceed to solve this problem in Matlab.
May be, it would be useful to solve the problem as : A*X + B*sqrt(1-X^2) = C.
I would greatly appreciate any help, ideas or advices
Thanks in advance
If I understood you correctly, you could use fsolve like this (c and X are vectors):
A = ones(2,2);
B = ones(2,2);
c = ones(2,1);
% initial point
x0 = ones(length(A), 1);
% call to fsolve
sol = fsolve(#(x) A * cos(x) + B*sin(x) - c, x0);
Here, we solve the nonlinear equation system F(x) = 0 with F: R^N -> R^N and F(x) = A * cos(x) + B*sin(x) - c.
Only for the sake of completeness, here's my previous answer, i.e. how one could do it in case C and X are matrices instead of vectors:
A = ones(2,2);
B = ones(2,2);
C = ones(2,2);
% initial point
x0 = ones(numel(A), 1);
% call to fsolve
fsolve(#(x) fun(x, A, B, C), x0)
function [y] = fun(x, A, B, C)
% Transform the input vector x into a matrix
X = reshape(x, size(A));
% Evaluate the matrix equation
Y = A * cos(X) + B*sin(X) - C;
% flatten the matrix Y to a row vector y
y = reshape(Y, [], 1);
end
Here, the idea is to transform the matrix equation system F: R^(N x N) -> R^(N x N) into a equivalent nonlinear system F: R^(N*N) -> R^(N*N).

Solving system of three equations with three unknown variables

I am trying to solve a system of three equations with three unknown variables.
A1=(x+y)/2+(x-y)/2*cos(2*phi)+z*sin(2*phi)/2
A2=(x+y)/2-(x-y)/2*cos(2*phi)-z*sin(2*phi)/2
A3=-(x-y)/2*sin(2*phi)+z*cos(2*phi)
where A1, A2, A3, and phi are known and x,y, and z are unknown.
I used below code but it does not work. I got the solution as symbols.
clear;
clc;
A1=50;
A2=37.5;
A3=125.6;
phi=28;
syms x y z
eqn1 = (x+y)/2+(((x-y)/2)*cosd(2*phi))+(z*sind(2*phi))/2== A1;
eqn2 = (x+y)/2+(((x-y)/2)*cosd(2*phi))-(z*sind(2*phi))/2== A2;
eqn3 = (((x-y))*sind(2*phi))+(z*cosd(2*phi))== A3;
[A,B] = equationsToMatrix([eqn1, eqn2, eqn3], [x, y, z]);
X_1 = linsolve(A,B);
Thanks
You can skip using equationsToMatrix and linsolve and just use solve. You are already using the symbolics toolbox, so why would you want to convert the system into a matrix of coefficients and solve it that way? Just use the actual equations directly.
A1=50;
A2=37.5;
A3=125.6;
phi=28;
syms x y z
eqn1 = (x+y)/2+(((x-y)/2)*cosd(2*phi))+(z*sind(2*phi))/2== A1;
eqn2 = (x+y)/2+(((x-y)/2)*cosd(2*phi))-(z*sind(2*phi))/2== A2;
eqn3 = (((x-y))*sind(2*phi))+(z*cosd(2*phi))== A3;
[X, Y, Z] = solve(eqn1, eqn2, eqn3);
I get:
X = (sym)
69370560820559
──────────────
926177760500
Y = (sym)
-61526962823521
────────────────
926177760500
Z = (sym)
2910
────
193
Note that I'm using Octave instead of MATLAB (on my current system, I don't have access to the symbolic toolbox) so the output may be a bit different in format. You probably also want this in real (floating-point) form, so an additional cast to double for the outputs should help:
X = double(X);
Y = double(Y);
Z = double(Z);
By doing this, we get:
>> format long g;
>> X
X = 74.8998343288972
>> Y
Y = -66.4310518429048
>> Z
Z = 15.0777202072539

Taylor Method ODE

I am trying to implement the Taylor method for ODEs in MatLab:
My code (so far) looks like this...
function [x,y] = TaylorEDO(f, a, b, n, y0)
% syms t
% x = sym('x(t)'); % x(t)
% f = (t^2)*x+x*(1-x);
h = (b - a)/n;
fprime = diff(f);
f2prime = diff(fprime);
y(0) = y0,
for i=1:n
T((i-1)*h, y(i-1), n) = double(f((i-1)*h, y(i-1)))+(h/2)*fprime((i-1)*h, y(i-1))
y(i+1) = w(i) + h*T(t(i), y(i), n);
I was trying to use symbolic variables, but I don´t know if/when I have to use double.
I also tried this other code, which is from a Matlab function, but I do not understand how f should enter the code and how this df is calculated.
http://www.mathworks.com/matlabcentral/fileexchange/2181-numerical-methods-using-matlab-2e/content/edition2/matlab/chap_9/taylor.m
As error using the function from this link, I got:
>> taylor('f',0,2,0,20)
Error using feval
Undefined function 'df' for input arguments of type 'double'.
Error in TaylorEDO (line 28)
D = feval('df',tj,yj)
The f I used here was
syms t
x = sym('x(t)'); % x(t)
f = (t^2)*x+x*(1-x);
This is a numerical method, so it needs numerical functions. However, some of them are computed from the derivatives of the function f. For that, you need symbolic differentiation.
Relevant Matlab commands are symfun (create a symbolic function) and matlabFunction (convert a symbolic function to numerical).
The code you have so far doesn't seem salvageable. You need to start somewhere closer to basics, e.g., "Matlab indices begin at 1". So I'll fill the gap (computation of df) in the code you linked to. The comments should explain what is going on.
function [T,Y] = taylor(f,a,b,ya,m)
syms t y
dfs(1) = symfun(f, [t y]); % make sure that the function has 2 arguments, even if the user passes in something like 2*y
for k=1:3
dfs(k+1) = diff(dfs(k),t)+f*diff(dfs(k),y); % the idea of Taylor method: calculate the higher derivatives of solution from the ODE
end
df = matlabFunction(symfun(dfs,[t y])); % convert to numerical function; again, make sure it has two variables
h = (b - a)/m; % the rest is unchanged except one line
T = zeros(1,m+1);
Y = zeros(1,m+1);
T(1) = a;
Y(1) = ya;
for j=1:m
tj = T(j);
yj = Y(j);
D = df(tj,yj); % syntax change here; feval is unnecessary with the above approach to df
Y(j+1) = yj + h*(D(1)+h*(D(2)/2+h*(D(3)/6+h*D(4)/24)));
T(j+1) = a + h*j;
end
end
Example of usage:
syms t y
[T, Y] = taylor(t*y, 0, 1, 2, 100);
plot(T,Y)

Making a function in terms of a sum from 1 to n in Matlab

I'm trying to get Matlab to take this as a function of x_1 through x_n and y_1 through y_n, where k_i and r_i are all constants.
So far my idea was to take n from the user and make two 1×n vectors called x and y, and for the x_i just pull out x(i). But I don't know how to make an arbitrary sum in MATLAB.
I also need to get the gradient of this function, which I don't know how to do either. I was thinking maybe I could make a loop and add that to the function each time, but MATLAB doesn't like that.
I don't believe a loop is necessary for this calculation. MATLAB excels at vectorized operations, so would something like this work for you?
l = 10; % how large these vectors are
k = rand(l,1); % random junk values to work with
r = rand(l,1);
x = rand(l,1);
y = rand(l,1);
vals = k(1:end-1) .* (sqrt(diff(x).^2 + diff(y).^2) - r(1:end-1)).^2;
sum(vals)
EDIT: Thanks to #Amro for correcting the formula and simplifying it with diff.
You can solve for the gradient symbolically with:
n = 10;
k = sym('k',[1 n]); % Create n variables k1, k2, ..., kn
x = sym('x',[1 n]); % Create n variables x1, x2, ..., xn
y = sym('y',[1 n]); % Create n variables y1, y2, ..., yn
r = sym('r',[1 n]); % Create n variables r1, r2, ..., rn
% Symbolically sum equation
s = sum((k(1:end-1).*sqrt((x(2:end)-x(1:end-1)).^2+(y(2:end)-y(1:end-1)).^2)-r(1:end-1)).^2)
grad_x = gradient(s,x) % Gradient with respect to x vector
grad_y = gradient(s,y) % Gradient with respect to y vector
The symbolic sum and gradients can be evaluated and converted to floating point with:
% n random data values for k, x, y, and r
K = rand(1,n);
X = rand(1,n);
Y = rand(1,n);
R = rand(1,n);
% Substitute in data for symbolic variables
S = double(subs(s,{[k,x,y,r]},{[K,X,Y,R]}))
GRAD_X = double(subs(grad_x,{[k,x,y,r]},{[K,X,Y,R]}))
GRAD_Y = double(subs(grad_y,{[k,x,y,r]},{[K,X,Y,R]}))
The gradient function is the one overloaded for symbolic variables (type help sym/gradient) or see the more detailed documentation online).
Yes, you could indeed do this with a loop, considering that x, y, k, and r are already defined.
n = length(x);
s = 0;
for j = 2 : n
s = s + k(j-1) * (sqrt((x(j) - x(j-1)).^2 + (y(j) - y(j-1)).^2) - r(j-1)).^2
end
You should derive the gradient analytically and then plug in numbers. It should not be too hard to expand these terms and then find derivatives of the resulting polynomial.
Vectorized solution is something like (I wonder why do you use sqrt().^2):
is = 2:n;
result = sum( k(is - 1) .* abs((x(is) - x(is-1)).^2 + (y(is) - y(is-1)).^2 - r(is-1)));
You can either compute gradient symbolically or rewrite this code as a function and make a standard +-eps calculation. If you need a gradient to run optimization (you code looks like a fitness function) you could use algorithms that calculate them themselves, for example, fminsearch can do this