How can I solve equation systems in MATLAB? - matlab

This is my code to solve equation systems.
Something is wrong with my code but I can't fix it.
D=1
E=2
F=3
syms a b c;
S= solve('a+b-c=D','2*+b-3*c=E','a-2*b=F')
S = [S.a S.b S.c]

Fixing your problem with symbolic solving
Looking at the documentation for solve, you can see an example for how to input equations to the solve function. They should not be strings (like you have done), but instead they should be equations using == in place of =.
Docs example:
syms x
solx = solve(sin(x) == 1,x)
Applying this to your system:
D=1; E=2; F=3;
syms a b c;
S = solve(a+b-c==D, 2*b-3*c==E, a-2*b==F);
S = [S.a S.b S.c];
% Ouput:
% S = [5/7, -8/7, -10/7]
Note, in the above example I have replaced *+ in your second equation with *. Use either * or +, but not both! I'm assuming this was a typo, it is not the root of your problems.
Another option without using symbolic maths
You can solve this without the symbolic math toolbox too. Your equations can be written as
1a + 1b - 1c = D
0a + 2b - 3c = E
1a - 2b + 0c = F
Which, in matrix form, is the same as
1 1 -1 a D
0 2 -3 * b = E
1 -2 0 c F
Using matrix operations, this can be solved by pre-multiplying both sides by the inverse of the 3x3 matrix. In MATLAB, getting this result is easy:
% Set up 3x3 matrix of coefficients
coeffs = [1 1 -1; 0 2 -3; 1 -2 0];
% Set up left hand side vector
DEF = [1; 2; 3];
% Solve
S = coeffs\DEF;
% Ouput
% S = [0.7143, -1.1429, -1.4286]
This output is the same as before, although clearly not in exact fractional form, since that is inherited from a,b and c being symbolic.
Edit:
Some things to consider about solving matrix equations in MATLAB, as prompted by Dev-iL's comment...
The backslash \ operator I've used above is shorthand for MATLAB's mldivide function
As noted in the above linked docs, they are interchangeable:
x = mldivide(A,B) is an alternative way to execute x = A\B
Also in the docs are notes on how \ works:
If A is a square matrix, A\B is roughly equal to inv(A)*B, but MATLAB processes A\B differently and more robustly.
In particular, MATLAB automatically chooses the most efficient algorithm for solving the system. Example decision flows can be seen in the docs, I will not replicate here as it is beyond the scope of the question.
The versatility of mldivide in solving linear systems stems from its ability to take advantage of symmetries in the problem by dispatching to an appropriate solver.
In summary:
Whilst mathematically "pre-multiplying by the inverse of the coeffs matrix" gives the solution to the system, using the backslash operator (a.k.a mldivide) is the MATLAB-esque way to solve this problem.
How does this extension relate to your original question? Hopefully you are better informed about which methods can be used for this problem. In particular, know that (unless needed for your particular situation) you can do this task easily (in less lines, quicker) without relying on MATLAB's symbolic math toolbox.

Related

matlab solving numerical differential equations [pic]

I'm trying to solve this numerical differential equations, can someone help?
clc;
clear;
syms A1(z) A2(z)
lamda1 = 1560*(10^-9);
c=3*(10^8);
d_eff=27*(10^-12);
omga1=(2*pi*c)/(lamda1);
omga2=omga1*2;
n=2.2;
k1=(n*omga1)/c;
k2=(n*omga2)/c;
ode1 = diff(A1) == (2*i*(omga1^2)*d_eff*A2*conj(A1)*exp(-i*(2*k1-k2)*z))/(k1*(c^2));
ode2 = diff(A2) == (i*(omga2^2)*d_eff.*(A1.^2).*exp(i*(2*k1-k2)*z))/(k2*(c^2));
odes = [ode1; ode2];
cond1 = A1(0) == 1;
cond2 = A2(0) == 0;
conds = [cond1; cond2];
M = matlabFunction(odes)
sol = ode45(M(1),[0 20],[2 0]);
in this question both ODE are coupled, hence there's only 1 ODE to solve:
1.- use 1st equation to write
A1=f(A2,dA2/dz)
and feed this expression into 2nd equation.
2.- regroup
n1=1j*k1^4/k2^2*1/deff*.25
n2=1j*3*(k1-k2)
now the ODE to solve is
y'=n1/y^2*exp(n2*z)
3.- It can obviously be done in MATLAB, but for this particular ODE in my opinion the Wolfram online ODE Symbolic Solver does a better job.
Input the obtained ODE of previous point into the ODE solver available in this link
https://www.wolframalpha.com/input?i=y%27%27+%2B+y+%3D+0
and solve
4.- The general (symbolic) solutions for A2 are
Note that I used k1 instead of n1 and k2 instead of n2 just in the Wolfram ODE Solver.
Rewording ; the k1 k2 expressions of the general solutions are not the wave numbers k1 k2 of the equations in the question. Just replace accordingly.
5.- Now get A1 using expression in point 2.
6.- I have spotted 2 possible errors in the MATLAB code posted in the question that shouldn't be ignored by the question originator:
In the far right side of the posted MATLAB code, the exponential expressions
6.1.- both show
exp(-i(2*k1-k2)z))/(k1(c^2))
there's this (k1*(c^2)) dividing the exponent wheras in the question none of the exponentials show such denominator their respective exponents.
6.2.- the dk or delta k expression in the exponentials of the question are obviously k2-k1 or k1-k2 , here there may be room for a sign ambiguity, that may shoot a wave solution onto the opposite direction, yet the point here is where
*exp(-1i*(2*k1-k2)*z)
should probably be
*exp(-1i*2*(k1-k2)*z)
or just
exp(-1i*(k1-k2)*z)
6.3.- and yes, in MATLAB (-1)^.5 can be either expressed with 1j or 1i but as written in the MATLAB code made available in the question, since only a chunk of code has been made available, it's fair to assume that no such i=1j has been done.

Solving system of linear equations

My goal is to solve the system of equation known as Lyapunov equation, that is finding x in the following equation:
A*X + X*transpose(A) +Q = 0
plus another linear constraint that is X*v = 0
where all matrices A, X ,Q are n by n matrices and v is a vector with length n.
How can I find such X in matlab?
Solution
Solving Lyapunov equations in Matlab is very easy. Both the continuous and discrete Lyapunov equation have a built-in function:
Continuous Lyapunov equation: lyap (see Matlab documentation here)
Discrete Lyapunov equation: dlyap (see Matlab documentation here)
Extra note: if the links would not work, or you want a quick way to check the documentation of a Matlab function offline, every built-in Matlab function has a short help page reachable by help NameOfTheFunction.
Furthermore the extended help page, as also visible on the web, with examples can also be retrieved offline by typing doc NameOfTheFunction in the Matlab terminal.
Example
Given the following continuous Lyapunov equation:
A*X + X*transpose(A) + Q = 0
The solution in Matlab for a stable A and positive definite Q is given as:
X = lyap(A,Q)
In some cases the equation is slightly different:
A*X + X*B + C = 0
This equation calls the Sylvester equation and is again solvable with the built-in Lyapunov function of Matlab:
X = lyap(A,B,C)
The same analogue solution steps exist for the discrete case, where the Lyapunov and Sylvester equation look slightly different:
A*X*transpose(A) -X + Q = 0 -> X = dlyap(A,Q)
A*X*B - X + C = 0 -> X = dlyap(A,B,C)

Understanding Matlab linsolve

1.What is the difference between A\b and linsolve(A,b) (different algorithms?) ?
2.What is the difference solving A*x=b and A'*A*x=A'*b, which is more precise ?
Second equation goes from Least squares approximation
Simple matlab test code:
A=[1,2,3;4,5,6;7,8,9]
b=[1;2;3]
x1= A\b
x1 =
-0.3333
0.6667
0
x2=linsolve(A,b)
x2 =
-0.3333
0.6667
0
x3=linsolve(A'*A,A'*b)
x3 =
0.2487
-0.4974
0.5820
x4=(A'*A)\(A'*b)
x4 =
-0.8182
1.6364
-0.4848
reading linsolve documentation I found that
[X,R] = linsolve(A,B) solves the matrix equation AX = B and returns
the reciprocal of the condition number of A if A is a square matrix,
and the rank of A otherwise.
so using R we can test precision(2nd question)?
Regarding your first question: one can consider mldivde (x = A\B) as a wrapper of the linsolve function. The function linsolve allows the user to specify information about the matrix A which can help Matlab to select a more appropriate (faster) algorithm to solve the system. Nevertheless, by using linsolve it is easy to screw up. Quoting from Matlab's documentation:
If A does not have the properties that you specify in opts, linsolve returns incorrect results and does not return an error message. If you are not sure whether A has the specified properties, use mldivide instead.
If you can assess with 100% of certainty the type of your matrix A while executing your algorithm, then go for linsolve. Otherwise use mldivide.

Doing a derivative in MatLab

As the title suggests, I am wondering how I can find the derivative of a 'function'. I am unsure what to do because I really do not have a function defined, just an array of values. So lets try a simple example:
x = 1:5;
y = x.^2
y =
1 4 9 16 25
As expected. Now I want to take the derivative. I know that this is 2x. Possibly use the diff function, as if in symbolic toolkit?
diff(y)
ans =
3 5 7 9
This looks like either 2x +// 1, with length length(y)-1. Is there any way I can compute the derivative of this and get a vector of length(y)?
I do not have the symbolic toolkit.
There is little you can do. This topic has already been discussed ad nauseum at the MathWorks web forums.
#noah has provided an example of numerical differentiation (ie: differencing) on a finite data set, whereas you are looking for a means of doing symbolic differentiation of continuous-domain-continuous-range function applied to a discrete-domain data set.
In short, not happening. You're asking how to install a shelf without a hammer, screw driver, or nails. You could always just download and install GNU Octave, a free alternative to MATLAB.
References.
"Symbolic Math In MATLAB" http://faraday.elec.uow.edu.au/subjects/annual/ECTE313/Symbolic_Maths.pdf
"Symbolic differentiation without symbolic math toolbox" http://www.mathworks.com/matlabcentral/newsreader/view_thread/83397
"GNU Octave - Download" http://www.gnu.org/software/octave/
"Symbolic differentiation with GNU Octave" http://octave.1599824.n4.nabble.com/Examples-for-use-of-symbolic-toolbox-td1601724.html
Numerical differentiation is kind of tricky with small data sets. The best way I can think of offhand to do this is to explicitly create the function and then apply it to the data.
>> syms x y
>> y = x^2;
>> dy = diff(y);
>> dy
ans =
2*x
>> v = 1:5;
>> f = matlabFunction(dy);
>> f(v)
ans =
2 4 6 8 10
You have no symbolic toolbox and you want the symbolic derivative. Here is a suggestion: If you already know the derivative of the function you are trying to apply to your vector (with knowledge of basic calculus), just apply it directly to your vector. For example:
vector = [1 2 3 4 5] % intended function = x^2
result = 2*vector
vector = [1 2 3 4 5] % intended function = sin(x)
result = cos(vector)
Is there any function you are trying to apply which you don't already know the derivative?

RBF and pseudoinverse XOR

The problem i am trying to understand is easy but i cant seem to get the correct result in matlab. The actual problem is that i want to get the weight vectors of a 2 hidden layer input RBF using just the plain distance as a function, i.e. no Baysian or Gaussian function as my φ. I will use the function with 2 centres let's say 0,0 and 1,1. So this will give me a Matrix φ of:
[0 sqrt(2) ; 1 1; 1 1; sqrt(2) 0] *[w1; w2] = [0;1;1;0] As defined my the XOR function.
When i apply the pseudoinverse of the Φ in matlab * [0;1;1;0] though i get [0.33 ; 0.33] which is not the correct value which would allow me to get the correct output values [0;1;1;0].
i.e. .33 * sqrt(2) != 0 .
Can someone explain to me why this is the case?
I'll take a swag at this. The matrix, I'll call A, A = [0 sqrt(2) ; 1 1; 1 1; sqrt(2) 0] has full column rank, but not full row rank, i.e. rank(A) = 2. Then you essentially solve the system Ax = b, where x is your weighting vector. You could also just do x = A\b in Matlab, which is supposedly a much more accurate answer. I get the same answer as you. This is a very rough explanation, when your system can not be solved for a certain solution vector, it means that there exists no such vector x that can be solved for Ax = b. What Matlab does is try to estimate the answer as close as possible. I'm guessing you used pinv, if you look at the Matlab help it says:
If A has more rows than columns and is not of full rank, then the overdetermined least squares problem
minimize norm(A*x-b)
does not have a unique solution. Two of the infinitely many solutions are
x = pinv(A)*b
and
y = A\b
So, this appears to be your problem. I would recommend looking at your φ matrix if possible to come up with a more robust system. Hope this is useful.