Solving a MATLAB equation - matlab

I have the following equation:
((a^3)-(4*a^2))+[1 0 2;-1 4 6;-1 1 1] = 0
How do I solve this in MATLAB?

Here is one possibility:
% A^3 - 4*A^2 + [1 0 2;-1 4 6;-1 1 1] = 0
% 1) Change base to diagonalize the constant term
M = [1 0 2;-1 4 6;-1 1 1];
[V, L] = eig(M);
% 2) Solve three equations "on the diagonal", i.e. find a root of
% x^4 - 4*x^3 + eigenvalue = 0 for each eigenvalue of M
% (in this example, for each eigenvalue I choose the 3rd root,
% which happens to be real)
roots1 = roots([1 -4 0 L(1,1)]); r1 = roots1(3);
roots2 = roots([1 -4 0 L(2,2)]); r2 = roots2(3);
roots3 = roots([1 -4 0 L(3,3)]); r3 = roots3(3);
% 3) Build matrix solution and transform with inverse change of base
SD = diag([r1, r2, r3]);
A = V*SD*inv(V) % This is your solution
% The error should be practically zero
error = A^3 - 4*A^2 + [1 0 2;-1 4 6;-1 1 1]
norm(error)
(The error is actually of the order of 10^-14.)

Related

Matlab - How to perform operations on each row between two matrices?

I have two matrices each of which contains two vectors (each row is a vector):
u = [1 0 0; 2 0 0]
v = [1 1 0; 2 2 0]
I want to calculate two angles between the vectors of the corresponding rows in the matrices (angle between [1 0 0] , [1 1 0] and angle between [2 0 0] , [2 2 0]). In this example, both angles will be 45 degrees. So what I want is a new matrix like this:
angles = [45; 45]
When I try this:
u = [1 0 0; 2 0 0]
v = [1 1 0; 2 2 0]
dp = u(:,1) .* v(:,1) + u(:,2) .* v(:,2) + u(:,3) .* v(:,3);
angles = atan2d(norm(cross(u,v)),dp)
The anwser will be:
angles = [76.3670 ; 45.8683]
and when I try this (change norm to normr):
u = [1 0 0; 2 0 0]
v = [1 1 0; 2 2 0]
dp = u(:,1) .* v(:,1) + u(:,2) .* v(:,2) + u(:,3) .* v(:,3);
angles = atan2d(norm(crossr(u,v)),dp)
The anwser will be:
angles = [0 0 45.0000 ; 0 0 14.0362]
How can I make it calculate the angle between the vectors of each row?
Try:
u=[1 0 0;2 0 0];
v = [1 1 0;2 2 0];
atan2(cross(u,v,2),dot(u,v,2)) % radians
atan2d(cross(u,v,2),dot(u,v,2)) % degrees
The ,2 in the cross and dot functions specifies the dimension to operate, since you are storing each vector in a row.
There a discussion here, with many other ways to calculate, and you may find one more suitable to your particular case of application.

Quick Assembly of sparse matrix

I have indices
I = [nGrid x 9] matrix % mesh on fine grid (9 point rectangle)
J = [nGrid x 4] matrix % mesh on coarse grid (4 point rectangle)
Here, nGrid is large number depending on the mesh (e.g. 1.e05)
Then I want to do like
R_ref = [4 x 9] matrix % reference restriction matrix from fine to coarse
P_ref = [9 x 4] matrix % reference prolongation matrix from coarse to fine
R = sparse(size) % n_Coarse x n_Fine
P = sparse(size) % n_Fine x n_Coarse
for k = 1 : nGrid % number of elements on coarse grid
R(I(k,:),J(k,:)) = R_ref;
P(J(k,:),I(k,:)) = P_ref;
end
size is predetermined number.
Note that even if there is same index in (I,J), I do not want to accumulate. I just want to put stencils Rref and Pref at each indices respectively.
I know that this is very slow due to the data structure of sparse.
Usually, I use
sparse(row,col,entry,n_row,n_col)
I can use this by manipulate I, J, R_ref, P_ref by bsxfun and repmat.
However, this cannot be done because of the accumulation of sparse function
(if there exists (i,j) such that [row(i),col(i)]==[row(j),col(j)], then R(row(i),row(j)) = entry(i)+entry(j))
Is there any suggestion for this kind of assembly procedure?
Sample code
%% INPUTS
% N and M could be much larger
N = 2^5+1; % number of fine grid in x direction
M = 2^5+1; % number of fine grid in y direction
% [nOx * nOy] == nGrid
nOx = floor((M)/2)+1; % number of coarse grid on x direction
nOy = floor((N)/2)+1; % number of coarse grid on y direction
Rref = [4 4 -1 4 -2 0 -1 0 0
-1 -1 -2 4 4 4 -1 4 4
-1 -1 4 -2 4 -2 4 4 -1
0 4 4 0 0 4 -1 -2 -1]/8;
Pref = [2 1 0 1 0 0 0 0 0
0 0 0 1 1 1 0 1 2
0 0 1 0 1 0 2 1 0
0 2 1 0 0 1 0 0 0]'/2;
%% INDEX GENERATION
tri_ref = reshape(bsxfun(#plus,[0,1,2]',[0,N,2*N]),[],1)';
TRI_ref = reshape(bsxfun(#plus,[0,1]',[0,nOy]),[],1)';
I = reshape(bsxfun(#plus,(1:2:N-2)',0:2*N:(M-2)*N),[],1);
J = reshape(bsxfun(#plus,(1:nOy-1)',0:nOy:(nOx-2)*nOy),[],1);
I = bsxfun(#plus,I,tri_ref);
J = bsxfun(#plus,J,TRI_ref);
%% THIS PART IS WHAT I WANT TO CHANGE
R = sparse(nOx*nOy,N*M);
P = R';
for k = 1 : size(I,1)
R(J(k,:),I(k,:)) = Rref;
P(I(k,:),J(k,:)) = Pref;
end

How to formulate this expression

I am new to MATLAB and I want to formulate the following lease square expression in Matlab. I have some codes that I am typing here. But the optimization problem solution seems not to be correct. Does anyone has an idea why?
First, I want to solve the heat equation
$$T_t(x,t) = - L_x . T(x,t) + F(x,t)$$
where L_x is Laplacian matrix of the graph.
then find y from the following least square.
$$ \min_y \sum_{j} \sum_{i} (\hat{T}_j(t_i) - T_j(t_i, y))^2$$
Thanks in advance!!
Here is my code:
%++++++++++++++++ main ++++++++++++++++++++
% incidence matrix for original graph
C_hat = [ 1 -1 0 0 0 0;...
0 1 -1 0 0 -1;...
0 0 0 0 -1 1;...
0 0 0 1 1 0;...
-1 0 1 -1 0 0];
% initial temperature for each vertex in original graph
T_hat_0 = [0 7 1 9 4];
[M_bar,n,m_bar,T_hat_heat,T_hat_temp] = simulate_temp(T_hat_0,C_hat);
C = [ 1 1 -1 -1 0 0 0 0 0 0;...
0 -1 0 0 1 -1 1 0 0 0;...
0 0 1 0 0 1 0 -1 -1 0;...
0 0 0 1 0 0 -1 0 1 -1;...
-1 0 0 0 -1 0 0 1 0 1];
%
% initial temperature for each vertex in original graph
T_0 = [0 7 1 9 4];
%
% initial temperature simulation
[l,n,m,T_heat,T_temp] = simulate_temp(T_0,C);
%
% bounds for variables
lb = zeros(m,1);
ub = ones(m,1);
%
% initial edge weights
w0 = ones(m,1);
% optimization problem
% w = fmincon(#fun, w0, [], [], [], [], lb, ub);
%++++++++++++++++++++ function++++++++++++++++++++++++++++
function [i,n,m,T_heat,T_temp] = simulate_temp(T,C)
%
% initial conditions
delta_t = 0.1;
M = 20; %% number of time steps
t = 1;
[n,m] = size(C);
I = eye(n);
L_w = C * C';
T_ini = T';
Temp = zeros(n,1);
% Computing Temperature
%
for i=1:M
K = 2*I + L_w * delta_t;
H = 2*I - L_w * delta_t;
%
if i == 1
T_heat = (K \ H) * T_ini;
%
t = t + delta_t;
else
T_heat = (K \ H) * Temp;
%
t = t + delta_t;
end
% replacing column of T_final with each node temperature in each
% iteration. It adds one column to the matrix in each step
T_temp(:,i) = T_heat;
%
Temp = T_heat;
end
end
%++++++++++++++++++ function+++++++++++++++++++++++++++++++++++++++++
function w_i = fun(w);
%
for r=1:n
for s=1:M_bar
w_i = (T_hat_temp(r,s) - T_temp(r,s)).^2;
end
end
To give a more clear answer, I need more information about what form you have the functions F_j and E_j in.
I've assumed that you feed each F_j a value, x_i, and get back a number. I've also assumed that you feed E_j a value x_i, and another value (or vector) y, and get back a value.
I've also assumed that by 'i' and 'j' you mean the indices of the columns and rows respectively, and that they're finite.
All I can suggest without knowing more info is to do this:
Pre-calculate the values of the functions F_j for each x_i, to give a matrix F - where element F(i,j) gives you the value F_j(x_i).
Do the same thing for E_j, giving a matrix E - where E(i,j) corresponds to E_j(x_i,y).
Perform (F-E).^2 to subtract each element of F and E, then square them element-wise.
Take sum( (F-E).^2**, 2)**. sum(M,2) will sum across index i of matrix M, returning a column vector.
Finally, take sum( sum( (F-E).^2, 2), 1) to sum across index j, the columns, this will finally give you a scalar.

How can I plot 3 equations with 3 variables in MATLAB?

I am trying to plot this system:
x1 - x2 + 3x3 = 8
2x1 - x2 + 4x3 = 11
- x1 + 2x2 -4x3 = -11
I tried with ezsurf and meshgrid, but I wasn't able to do it.
clc
clear all
close all
A = [1 -1 3; 2 -1 4; -1 2 -4];
B = [8 11 -11]';
C = [A B];
R = rref(C);
% R =
% 1 0 0 1
% 0 1 0 -1
% 0 0 1 2
D = R(:,4); % salvo la 4 colonna che contiene le soluzioni
disp('Le soluzioni del sistema proposto sono:');
disp(D);
figure(1);
hold on
grid on
syms x y z
eq = x + y + 3*z - 8;
Z = solve(eq,z)
ezsurf('8/3 - y/3 - x/3');
scatter3(D(1),D(2),D(3));
How can I plot this system of equations?
Maybe I'm missing something, but you have 3 unknown x1, x2 and x3 for 3 equations, therefore there is a unique solution (provided the determinant of the matrix is not zero):
>> A = [1 -1 3; 2 -1 4; -1 2 -4];
>> B = [8 11 -11]';
>> x = A\B
x =
1
-1
2
So there is nothing to plot other than a single point?

Solve complex equations in MATLAB

I'm having problems in solving the following equations
A+B+C=0
D+E+3G=0
A+D+G=0
B+E+G=0
C+G=0
(0.74j)A-(0.74j)B-(22.5+10.89j)D+(3.75j)E=1
I have tried the solve command but it gave me an error for the last equation.
You have a fairly trivial linear problem of the form Ax = b, with
% A B C D E G
A = [1 1 1 0 0 0
0 0 0 1 1 3
1 0 0 1 0 1
0 0 0 0 1 1
0 0 1 0 0 1
0.74j -0.74j 0 (22.5+10.89j) 3.75j 0];
b = [0
0
0
0
0
1];
% x = [ <your factor A>
% <your factor B>
% <your factor C>
% <your factor D>
% <your factor E>
% <your factor G>];
%
% We have to solve for x.
You can solve this most easily with Matlab's backslash operator:
>> x = A\b
ans =
-0.017048398623080 + 0.009391773374804i % A
0.000000000000000 - 0.000000000000000i % B
0.017048398623080 - 0.009391773374804i % C
0.034096797246161 - 0.018783546749607i % D
0.017048398623080 - 0.009391773374804i % E
-0.017048398623080 + 0.009391773374804i % G
Observe that
B == 0
C == -A == E == -G == D/2