solving large number of simultaneous linear equations
2 views (last 30 days)
Show older comments
Kamal Bera
on 21 Apr 2017
Commented: Walter Roberson
on 21 Apr 2017
Suppose I am solving the following problem:
dK=sym('dK',[2 2]);
I_LHS=[3 4;2 2]*dK*[1 2;1 1];
I_RHS=[36 47;20 26];
eqn1=I_LHS(1,1)==I_RHS(1,1);eqn2=I_LHS(1,2)==I_RHS(1,2);
eqn3=I_LHS(2,1)==I_RHS(2,1);eqn4=I_LHS(2,2)==I_RHS(2,2);
eqns=[eqn1,eqn2,eqn3,eqn4];
Sol=vpasolve(eqns);
dK=double([Sol.dK1_1,Sol.dK1_2;Sol.dK2_1,Sol.dK2_2])
the solution it is giving is dK=[1 3;2 4], which is absolutely fine. Now for my actual larger problem (having 11200 equations and 11200 variables) it is really difficult to implement this way, because I have to write eqn1=I_LHS(1,1)==I_RHS(1,1);........;eqn11200=I_LHS(20,560)==I_RHS(20,560); and eqns=[eqn1,.....;eqn11200]; and so for dK of last line of code. Note that obtaining dK is just a part of my original code. In fact for this large problem MATLAB shows: " earlier syntax errors confuse code analyzer (or a possible analyzer bug)" at the end of for loop of the code. Can anyone help me to solve this problem is a better way?
0 Comments
Accepted Answer
Walter Roberson
on 21 Apr 2017
eqns = I_LHS - I_RHS;
sol = solve(eqns);
dK = reshape( structfun(@double, sol), size(I_LHS.')) .';
Notice the two transposes. My tests indicate that the field names of the sol structure would be in the order
dK1_1: [1×1 sym]
dK1_2: [1×1 sym]
dK2_1: [1×1 sym]
dK2_2: [1×1 sym]
which is row order fastest. To convert to column order fastest as is needed for your dK array, you reshape with the number of columns as the first size, and then transpose.
3 Comments
Bjorn Gustavsson
on 21 Apr 2017
Why such an obfuscated solution? Why not using something that looks sensible:
M1 = vpa([3,4;2 2]);
M2 = vpa([1 2;1 1]);
I_RHS = vpa([36 47;20 26]);
dK = M1\(I_RHS/M2);
Nice neat clean, linear equations solved as linear equations should be solved.
Walter Roberson
on 21 Apr 2017
In my opinion, using both mldivide and mrdivide in an expression is more obfuscated than solve.
More Answers (1)
Bjorn Gustavsson
on 21 Apr 2017
If you simply use the standard numerical matrix capabilities of matlab something like this should be your solution:
% I_LHS == [3 4;2 2]*dK*[1 2;1 1]
M1 = [3 4;2 2];
M2 = [1 2;1 1];
% I_LHS == M1*dK*M2
% I_LHS/M2 == M1*dK
% M1\(I_LHS/M2) == dK
dK = M1\(I_LHS/M2)
Provided that your larger matrices are well-conditioned.
HTH
0 Comments
See Also
Categories
Find more on Symbolic Math Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!