Search code examples
matlabsymbolic-math

How to call automatically symbolic variables in a loop in Matlab


Is there anyway to use a loop index to call symbolic variables in Matlab? For example, consider the following code whose goal is to store the symbolic expression "x1+x2+x3" in "y".

syms x1 x2 x3
y = 0;

for i = 1:3
    y = y + xi;
end

The code does not work because on each iteration Matlab reads "y = y + xi" and returns the error "xi is undefined", instead of reading "y = y + x1", "y = y + x2" and "y = y + x3", is there anyway around this?

Thanks.


Solution

  • If your Matlab does not support the matrix declaration of symbolics directly (as sym('x',[3 1])) you can write your own function for that:

    function out = Matrix_Sym(name, size) %#ok<STOUT>
    
    rows = size(1);
    cols = size(2);
    
    S = '';
    for k1 = 1:rows
        for k2 = 1:cols
            if rows == 1
                S = [S name int2str(k2) ' '];
            elseif cols == 1
                S = [S name int2str(k1) ' '];
            else
                S = [S name int2str(k1) int2str(k2) ' '];
            end
        end
    end
    
    eval(['syms ' S]);
    
    eval (['out = reshape([' S '], [rows, cols]);']);
    

    Then you could get the same result with:

    x = Matrix_Sym('x', [3 1])
    ...