Gwendolyn Ward
Gwendolyn Ward

Reputation: 1

Matlab solve system of equations with fore loops faster

I'm working on code in Matlab that involves graphing solutions to a system of equations. Right now, the only way I know of doing it is like this:

E = 200000; v = .3;    
S = [1/E, -v/E, -v/E; 
-v/E, 1/E, -v/E; 
-v/E, -v/E, 1/E];
e1 = linspace(0,eu,52);
sig10 = zeros(size(e1));
syms e2; syms e3; syms sig1;

a = 0;
for k = 1:52
    sig = (S^-1)*[e1(k); e2; e3];
    eq1 = sig(3,1) == 0;
    eq2 = sig(2,1) == a*sig1;
    eq3 = sig(1,1) == sig1;
    [solsig, sol2, sol3] = solve([eq1, eq2, eq3], [sig1, e2, e3]);
    sig10(1,k) = solsig;
end

There are several other loops like this. It works, however it takes forever to execute. I've tried solving the system outside the loop symbolically, but I can't figure out how to put back in the k variable where it is needed. Also, since I realize there might be an easy way to go about this since it's a matrix problem, here's another code that's giving me similar issues:

syms tous; syms sigs1; syms sigs2;
sigxhill = zeros(1,361);

for t=0:360
    alpha = t;
    eq1 = sigsx == sig1*cosd(alpha)^2+sigs2*sind(alpha)^2;
    eq2 = 0 == sig1*sind(alpha)^2+sigs2*cosd(alpha)^2;
    eq3 = tous == (sig1 - sigs2)*sind(alpha)*cosd(alpha);
    eq4 = 2*sig0^2 == F*sigys^2+G*sigsx^2+H*(sigsx-sigsy)^2+2*N*tous^2;
    sol1 = solve([eq1, eq2, eq3, eq4], [sigsx, tous, sigs1, sigs2]);
    sigxhill(1,t+1) = sol1.sigsx(1); touhill(1,t+1) = sol1.tous(1);
    sig1hill(1,t+1) = sol1.sigs1(1); sig2hill(1,t+1) = sol1.sigs2(1);
end

Does anybody have any ideas?

Upvotes: 0

Views: 114

Answers (1)

bushmills
bushmills

Reputation: 673

Unfortunately I can' t execute your code, because I haven't the Symbolic Math Toolbox installed. But in thoses cases a good way to start is using the MATLAB Profiler:

profile on;
E = 200000; v = .3;    
S = [1/E, -v/E, -v/E; 
-v/E, 1/E, -v/E; 
-v/E, -v/E, 1/E];
e1 = linspace(0,eu,52);
sig10 = zeros(size(e1));
syms e2; syms e3; syms sig1;

a = 0;
for k = 1:52
    sig = (S^-1)*[e1(k); e2; e3];
    eq1 = sig(3,1) == 0;
    eq2 = sig(2,1) == a*sig1;
    eq3 = sig(1,1) == sig1;
    [solsig, sol2, sol3] = solve([eq1, eq2, eq3], [sig1, e2, e3]);
    sig10(1,k) = solsig;
end
profile viewer;

This should give you some additional information about the parts of code, which need most of the execution time.

See also the Documentation for some further information:

http://de.mathworks.com/help/matlab/ref/profile.html

Upvotes: 0

Related Questions