0

I'm trying to solve a symbolic system of equations for many variables. The structure of the equations will change based on the entries of AM, so solving these equations casually won't work well. This code does what I expect it to, however I need to solve for approximately 20,000 cases, so it is too slow. Is there any way to speed it up (possibly using vectorization?).

syms FD ICE EM GEN

AM = [0 1 1 0 ;
     0 1 0 0 ;
     0 0 1 0;
    0 0 0 1];

Tvec = [FD;ICE;EM;GEN]

eqs=  AM * Tvec  ==   Tvec

tic

%Start solving for different cases in loop.  This is really slow!
for j = 1:100

    FDv = j;
    ICEv = j^2;

    ans = solve(eqs, FD == FDv, ICE == ICEv);

    FD_ans(j)=double(ans.FD);
    ICE_ans(j)=double(ans.ICE);
    EM_ans(j)=double(ans.EM);
end
toc

Edit: For clarification, in the future I plan to have the entries of AM as parameters. These entries will vary, but will only have 1 or 0 values.

  • @David: I am aware that my system is overdetermined, and I'm actually taking advantage of Matlab's symbolic toolbox to handle that. I'm trying to dynamically generate new equations based on the AM matrix. If GEN is unconstrained, I would like it to take a value of 0. – teh_allchemist Nov 14 '13 at 22:47
  • Sorry, just wanted to tidy up my previous comment. For this `AM` the solution is `FD=j`, `ICE=j^2`, `EM=j-j^2` and `GEN` is unconstrained. Since you have an overdetermined system, for a general `AM` there may be no solution, or infinite solutions (as in this case). What do you want to return in these cases? It may be more useful to write a system of 2 linear equations in 2 unknowns and solve using `\`. – David Nov 14 '13 at 22:50
  • 1
    I won't complain about the [use of `j` as a variable](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab), but *please*, do not use `ans` as a variable! That will cause nothing but bugs! – Stewie Griffin Nov 14 '13 at 22:58

2 Answers2

0

You may try to adopt your code to use with MATLAB parfor.

Michael
  • 1,505
  • 14
  • 26
0

This seems to work, but it's hard to find AM matrices that give consistent systems of equations.

AM = [0 1 1 0 ;
      0 1 0 0 ;
      0 0 1 0;
      0 0 0 1];

 tic

 %Start solving for different cases in loop.  This is really slow!
 for j = 1:100

    A=AM(1:2,1:2);
    B=AM(1:2,3:4);
    C=AM(3:4,1:2);
    D=AM(3:4,3:4);
    a1=B\((eye(2)-A)*[j;j^2]);a1(isnan(a1))=0;
    a2=(eye(2)-D)\(C*[j;j^2]);a2(isnan(a2))=0;

    if (AM-eye(4))*[j;j^2;a1]==zeros(4,1)
        FDa(j)=j;
        ICEa(j)=j^2;
        EMa(j)=a1(1);
        GENa(j)=a1(2);
    elseif (AM-eye(4))*[j;j^2;a2]==zeros(4,1)
        FDa(j)=j;
        ICEa(j)=j^2;
        EMa(j)=a2(1);
        GENa(j)=a2(2);
    else
        FDa(j)=NaN;
        ICEa(j)=NaN;
        EMa(j)=NaN;
        GENa(j)=NaN;
    end
end
toc
David
  • 8,449
  • 1
  • 22
  • 32