How to write many functions depending on each other in matlab - matlab

I have some functions are depending on each ther , the functions are from this book page 136 http://www.cs.helsinki.fi/u/ahyvarin/papers/bookfinal_ICA.pdf .. I functions are presented below , How to write following functions in matlab ??
y(t) = W(t-1)*x(t)
h(t) = P(t-1)*y(t)
P(t)=(1/B)*Tri[P(t-1)-m(t)*h^T(t)]
m(t) = h(t)/(B+y^T(t))*h(t))
e(t) = x(t)-W^T(t-1)*y(t)
W(t) = W(t-1) + m(t)*e^T(t)
It is solving the weight matrix W(t) iteratively .. I tried to do like this in matlab but I did not work so may be you can advice to correct the code :
for i=1:10
e=randn(3,5000);
A=[1 0 0;-0.5 0.5 0;0.3 0.1 0.1];
x=A*e;
y(t) = W(t-1)*x(t)
h(t) = P(t-1)*y(t)
P(t)=(1/B)*Tri[P(t-1)-m(t)*h^T(t)]
m(t) = h(t)/(B+y^T(t))*h(t))
e(t) = x(t)-W^T(t-1)*y(t)
W(t) = W(t-1) + m(t)*e^T(t)
end
Thanks

Ok. I can't really understand what you want, but your code shows that you don't understand some moments. I will try to clarify some moments to you:
for i = 2:10
x = rand(3);
y = W(:,:,i-1)*x;
h = P(:,:,i-1)*y;
m=h/(1+y'*h);
P(:,:,i)=P(:,:,i-1)*m*h';
e=x-W(:,:,i-1)'*y;
W(:,:,i)=W(:,:,i-1)+m*e';
end
You must go something like this: 1. you calculate x and use it to calculate other functions.
2. all of them are matrices. So you need to define it first. For example y = ones(3) etc. 3.Thats not y^T or e^T. Its transposing. If you do not feel difference it's early for you to solve this task :)
And the last: Tri function will create a some kind of problems to you, but it's defined at 136 page.
P.S. i missed beta becouse of don't know what is it :)

Related

Solving DDE in Matlab

I am trying to learn how to solve DDE (delay diff. eq) on Matlab and I am using a very helpful (Youtube-tutorial) where the guy solves examples. In the case of a 3-dimensional system, the code goes as follows:
tau = [1 0.5];
tf = 10;
sol = dde23(#dde,tau,#history,[0 tf]);
t = linspace(0,tf,200);
y = deval(sol,t);
figure(1)
plot(t,y)
function y = history(t)
y = [1;0;-1];
end
The dde function according to the tutorial is:
function dydt = dde(t,y,tau)
y1tau1 = tau(:,1);
y2tau2 = tau(:,2);
dydt = [y1tau1(1)
y(1) - y1tau1(1) + y2tau2(2)
y(2) - y(3)];
end
, where if I get it well, we have a 3by2 matrix with the state variables and their respective delays: the first column is about the first delay tau_1 for each of the three state variables, and the second column is for the tau_2.
Nevertheless, this matrix has only 2 non-zero components and they are the tau_1 delay for y_1 and the tau_2 for y_2.
Given that, I thought it would be the same (at least in this case where we only have one delay for y_1 and one for y_2) as if the function were:
function dydt = dde(t,y,tau)
dydt = [tau(1)
y(1) - tau(1) + tau(2)
y(2) - y(3)];
end
I ran the script for both of them and the results are totally different, both qualitatively and quantitatively, and I cannot figure out why. Could someone explain the difference?
y1tau1(1) and y2tau2(2) are tau(1,1) and tau(2,2)
while
tau(1) and tau(2) are the same as tau(1,1) and tau(2,1).
So the second one is different, there is no reason why the two different, if only slightly so, DDE systems should have the same solutions.
As you have also a general interpretation question, the DDE system is mathematically
dy1(t)/dt = y1(t-1)
dy2(t)/dt = y1(t) - y1(t-1) + y2(t-0.5)
dy3(t)/dt = y2(t) - y3(t)
It is unfortunate that the delayed values are also named tau, it would be better to use something else like yd,
function dydt = dde(t,y,yd)
dydt = [ yd(1,1)
y(1) - yd(1,1) + yd(2,2)
y(2) - y(3) ];
end
This yd has two columns, the first is the value y(t-tau(1))=y(t-1), the second column is y(t-tau(2))=y(t-0.5). The DDE function does not know the delays themselves, it only computes with the values at these delays. These are obtained from a piecewise interpolation function that continues the history function with the solution so far. The history function takes the place of the initial condition.

Strange wrong result for (un)coupled PDEs using MATLAB's pdepe, time is doubled

I am trying to solve two coupled reaction diffusion equations in 1d, using pdpe, namely
$\partial_t u_1 = \nabla^2 u_1 + 2k(-u_1^2+u_2)$
$\partial_t u_2 = \nabla^2 u_1 + k(u_1^2-u_2)$
The solution is in the domain $x\in[0,1]$, with initial conditions being two identical Gaussian profiles centered at $x=1/2$. The boundary conditions are absorbing for both components, i.e. $u_1(0)=u_2(0)=u_1(1)=u_2(1)=0$.
Pdepe gives me a solution without prompting any errors. However, I think the solutions must be wrong, because when I set the coupling to zero, i.e. $k=0$ (and also if I set it to be very small, say $k=0.001$), the solutions do not coincide with the solution of the simple diffusion equation
$\partial_t u = \nabla^2 u$
as obtained from pdepe itself.
Strangely enough, the solutions $u_1(t)=u_2(t)$ from the "coupled" case with coupling set to zero, and the solution for the case uncoupled by construction $u(t')$ coincide if we set $t'=2t$, that is, the solution of the "coupled" case evolves twice as fast as the solution of the uncoupled case.
Here's a minimal working example:
Coupled case
function [xmesh,tspan,sol] = coupled(k) %argument is the coupling k
std=0.001; %width of initial gaussian
center=1/2; %center of gaussian
xmesh=linspace(0,1,10000);
tspan=linspace(0,1,1000);
sol = pdepe(0,#pdefun,#icfun,#bcfun,xmesh,tspan);
function [c,f,s] = pdefun(x,t,u,dudx)
c=ones(2,1);
f=zeros(2,1);
f(1) = dudx(1);
f(2) = dudx(2);
s=zeros(2,1);
s(1) = 2*k*(u(2)-u(1)^2);
s(2) = k*(u(1)^2-u(2));
end
function u0 = icfun(x)
u0=ones(2,1);
u0(1) = exp(-(x-center)^2/(2*std^2))/(sqrt(2*pi)*std);
u0(2) = exp(-(x-center)^2/(2*std^2))/(sqrt(2*pi)*std);
end
function [pL,qL,pR,qR] = bcfun(xL,uL,xR,uR,t)
pL=zeros(2,1);
pL(1) = uL(1);
pL(2) = uL(2);
pR=zeros(2,1);
pR(1) = uR(1);
pR(2) = uR(2);
qL = [0 0;0 0];
qR = [0 0;0 0];
end
end
Uncoupled case
function [xmesh,tspan,sol] = uncoupled()
std=0.001; %width of initial gaussian
center=1/2; %center of gaussian
xmesh=linspace(0,1,10000);
tspan=linspace(0,1,1000);
sol = pdepe(0,#pdefun,#icfun,#bcfun,xmesh,tspan);
function [c,f,s] = pdefun(x,t,u,dudx)
c=1;
f = dudx;
s=0;
end
function u0 = icfun(x)
u0=exp(-(x-center)^2/(2*std^2))/(sqrt(2*pi)*std);
end
function [pL,qL,pR,qR] = bcfun(xL,uL,xR,uR,t)
pL=uL;
pR=uR;
qL = 0;
qR = 0;
end
end
Now, suppose we run
[xmesh,tspan,soluncoupled] = uncoupled();
[xmesh,tspan,solcoupled] = coupled(0); %coupling k=0, i.e. uncoupled solutions
One can directly check by plotting the solutions for any time index $it$ that, even if they should be identical, the solutions given by each function are not identical, e.g.
hold all
plot(xmesh,soluncoupled(it+1,:),'b')
plot(xmesh,solcoupled(it+1,:,1),'r')
plot(xmesh,solcoupled(it+1,:,2),'g')
On the other hand, if we double the time of the uncoupled solution, the solutions are identical
hold all
plot(xmesh,soluncoupled(2*it+1,:),'b')
plot(xmesh,solcoupled(it+1,:,1),'r')
plot(xmesh,solcoupled(it+1,:,2),'g')
The case $k=0$ is not singular, one can set $k$ to be small but finite, and the deviations from the case $k=0$ are minimal, i.e. the solution still goes twice as fast as the uncoupled solution.
I really don't understand what is going on. I need to work on the coupled case, but obviously I don't trust the results if it does not give the right limit when $k\to 0$. I don't see where I could be making a mistake. Could it be a bug?
I found the source of the error. The problem lies in the qL and qR variables of bcfun for the coupled() function. The MATLAB documentation, see here and here, is slightly ambiguous on whether the q's should be matrices or column vectors. I had used matrices
qL = [0 0;0 0];
qR = [0 0;0 0];
but in reality I should have used column vectors
qL = [0;0];
qR = [0;0];
Amazingly, pdpe didn't throw an error, and simply gave wrong results. This should perhaps be fixed by the developers.

Using MATLAB plots to find linear equation constants

Finding m and c for an equation y = mx + c, with the help of math and plots.
y is data_model_1, x is time.
Avoid other MATLAB functions like fitlm as it defeats the purpose.
I am having trouble finding the constants m and c. I am trying to find both m and c by limiting them to a range (based on smart guess) and I need to deduce the m and c values based on the mean error range. The point where mean error range is closest to 0 should be my m and c values.
load(file)
figure
plot(time,data_model_1,'bo')
hold on
for a = 0.11:0.01:0.13
c = -13:0.1:-10
data_a = a * time + c ;
plot(time,data_a,'r');
end
figure
hold on
for a = 0.11:0.01:0.13
c = -13:0.1:-10
data_a = a * time + c ;
mean_range = mean(abs(data_a - data_model_1));
plot(a,mean_range,'b.')
end
A quick & dirty approach
You can quickly get m and c using fminsearch(). In the first example below, the error function is the sum of squared error (SSE). The second example uses the sum of absolute error. The key here is ensuring the error function is convex.
Note that c = Beta(1) and m = Beta(2).
Reproducible example (MATLAB code[1]):
% Generate some example data
N = 50;
X = 2 + 13*random(makedist('Beta',.7,.8),N,1);
Y = 5 + 1.5.*X + randn(N,1);
% Example 1
SSEh =#(Beta) sum((Y - (Beta(1) + (Beta(2).*X))).^2);
Beta0 = [0.5 0.5]; % Initial Guess
[Beta SSE] = fminsearch(SSEh,Beta0)
% Example 2
SAEh =#(Beta) sum(abs(Y-(Beta(1) + Beta(2).*X)));
[Beta SumAbsErr] = fminsearch(SAEh,Beta0)
This is a quick & dirty approach that can work for many applications.
#Wolfie's comment directs you to the analytical approach to solve a system of linear equations with the \ operator or mldivide(). This is the more correct approach (though it will get a similar answer). One caveat is this approach gets the SSE answer.
[1] Tested with MATLAB R2018a

MatLab ode45 explanation

For a project I need to understand a matlab code, but as I am quite new I dont really understand what is happening. I have a function file and a script file.
Function:
function dxdt = sniffer_ode(t,x,par,tu)
X = x(1);
R = x(2);
k1 = par(1);
k2 = par(2);
k3 = par(3);
k4 = par(4);
S = interp1(tu(:,1),tu(:,2),t);
dxdt(1) = k3*S-k4*X;
dxdt(2) = k1*S-k2*X*R;
dxdt = dxdt(:); %dxdt should be column
and the script file:
%sniffer
close all
%initial conditions:
X0=0; R0=0;
x0=[X0 R0];
%parameters:
k1=1; k2=1; k3=1; k4=1;
par=[k1 k2 k3 k4];
%input:
tu=[ 0 , 0
1 , 0
1.01, 1
20 , 1];
[t,x] = ode45(#sniffer_ode,[0 20],x0, [],par,tu);
plot(t,x);
So the question is: What is happening? I also need to plot S in the same figure as X and R. How do I do this?
I appreciate your help!
This is a really basic Matlab question. There is tons of information about your requested topic. I think these slides will help you on the right path.
However, a quick explanation; the first code you provide is the function which describes your ordinary differential equation. This function always has to be of the form x' = f(t,x,...). Herein t is the time and x is the state. After the state (on the place of the dots ...) you can define other input parameters, such as is being done in your ode function. Furthermore, the interp1 function interpolates the data provided.
The second code you provide is the code you start within Matlab. Parameters are defined, after which the ordinary differential equation is solved and plotted.
If you have any further questions I would recommend that you first try to find your answer using a search engine.

MATLAB and function

I want to calculate the function y(t) from the equation:
y(t) = -3t^2+5, t>=0
y(t) = 3t^2+5, t<0
for -9 <= t <= with the step-size 0.5
And I want to plot it by using MATLAB. I approach this question in two ways:
First
t=0:0.5:9
y=-3*t^2+5
t1=-0.00000000001:0.5:-9
y1=3*t^2+5
plot(t,y,t1,y1)
Second by using loop
t=-9:0.5:9
if(t>=0)
y=-3*(t.^2)+5
else
y=3.*(t.^2)+5
end
plot(t,y)
My problem is the two ways above seem not to give the same answer... Which one is the correct answer?
You can use the sign function to do this particular example a little easier:
t = -9:0.5:9;
y = -sign(t)*3.*t.^2 + 5;
plot(t,y);
In your first attempt, your t1 definition should be:
t1 = 0:-0.5:-9;
Note the minus sign on the increment.
Using a "loop" you seem to have left out the actual loop part. Try something like
t = -9:0.5:9;
for idx = 1:length(t)
if t(idx) <= 0
y(idx) = -3*(t(idx).^2)+5
etc.
Here's a more idiomatic solution that avoids SIGN for cases where that's not the only difference.
t = -9:0.5:9
y = -3*t.^2+5
y(t<0) = 3*t(t<0).^2+5
plot(t, y)