Solving equations in a cell array

1.1k views Asked by At

I have some linear equations in a cell array like this ( The number of equations vary each time ) :

equs = { '2*X1+X2+6', '3*X2-X1' }

How can I solve these equation with Matlab? I can get my answer simply by this function :

ans = solve(equs(1), equs(2));

But, as the number of equations differ each time, I want this to be done automatically.

2

There are 2 answers

0
Andrey Rubshtein On

I am assuming that you want the equations to be equal to 0, and that no equals sign appears in the equations.

Parse the expressions to find the coefficients - put into a matrix (A). I am using here a near trick that assumes that the variables are always x1, x2, etc. Also you must write the * sign for multiplications. The FindCoeffs function finds the coefficients by assigning ones and zeros to the variables. Then, you can solve the equations using linsolve.

 function FindEquations() 

     a = {'x1+x2 - 6 ','x1 - x2 - 2'};
     A = [];
     B = [];
     for i=1:numel(a)
        [b,l] = FindCoeefs(a{i}, numel(a));
        A(end+1,:) = l;
        B(end+1) = -b;
    end
    linsolve(A,transpose(B))
end

function [b,p] = FindCoeefs(expr, n)
    for j=1:n
        eval(sprintf('x%d=0;',j));
    end
    b = eval([expr ';']);

    p = zeros(1,n);
    for i=1:n
        for j=1:n
            eval(sprintf('x%d=0;',j));
        end
        eval(sprintf('x%d=1;',i));

        p(i) = eval([expr ';']) - b;    
    end

end
0
ProfNitz On

You can solve equation stored in a cell array by using:

solve(equs{:})

Works for the unknown, too (in case they are not properly determined by symvar):

uvar={x,y}
solve(equs{:},uvar{:})