Search code examples
matlabsymbolic-math

Is there a MATLAB function to convert symbolic expressions to MATLAB code indexing?


Example: I have an array like this R = sym('R',[4 4]). I do some symbolic operations and get an expression, which is a function of stuff like R1_2, R2_2, etc. I'd like to paste the expression into some code, but I really want it to look like R(1,2), R(2,2) etc. Is there a function to do this, or do I need to manually find/replace 16 times?


Solution

  • You can substitute your variable R with a unknown function R:

    R = sym('R',[3 3]);
    M=det(R)
    funR = symfun(sym('R(x, y)'),[sym('x'),sym('y')]);
    for rndx=1:size(R,1)
        for cndx=1:size(R,2)
            M=subs(M,R(rndx,cndx),funR(rndx,cndx));
        end   
    end
    

    Output:

    R(1, 1)*R(2, 2)*R(3, 3) - R(1, 1)*R(2, 3)*R(3, 2) - R(1, 2)*R(2, 1)*R(3, 3) + R(1, 2)*R(3, 1)*R(2, 3) + R(2, 1)*R(1, 3)*R(3, 2) - R(1, 3)*R(2, 2)*R(3, 1)

    vectorized version of the code above (faster):

    [rndx,cndx]=ind2sub(size(R),1:numel(R));
    M2=subs(M,num2cell(R(:))',num2cell(funR(rndx,cndx)))