dunadar
dunadar

Reputation: 1785

Matlab symbolic matrix as argument of function instead of individual components variables

I want to export to file a symbolic expression that involves a matrix:

% M is a 2x2 symbolic matrix composed by M_1_1, M_1_2, M_2_1, M_2_2
M = sym('M_%d_%d', [2 2], 'real');
% s1 and s2 are scalar variables
syms('s1', 's2');
% Expression with M, s1 and s2
myExpr = M*[s1;s2];
% Store expression as matlab code in a function file
matlabFunction(myExpr, 'file', 'myExprFunc.m');

However, since the expanded expression is:

myExpr =

 M_1_1*s1 + M_1_2*s2
 M_2_1*s1 + M_2_2*s2

This creates a function with expanded input arguments (one per free variable):

function myExpr = myExprFunc(M_1_1, M_1_2, M_2_1, M_2_2, s1, s2)
...

With 20x20 matrices, this is nightmare. It would be nice to have a signature like

function myExpr = myExprFunc(M, s1, s2)

But nothing seem to work. The straigthforward approach matlabFunction(myExpr, 'file', 'myExprFunc.m', 'Vars', {'M', 's1', 's2'}); returns an error because the free variables M_x_y must appear as arguments. My current solution involves creating a wrapper function that assigns individual variables as M_x_y = M(x,y);, but it would be much better to get it done "the pretty way".

Do anybody knows a solution?

Upvotes: 4

Views: 125

Answers (1)

horchler
horchler

Reputation: 18484

Don't use strings, e.g., {'M', 's1', 's2'}, when working with symbolic math. This has been deprecated and direct support for such usage is disappearing with each Matlab version. To achieve what you want, you can use:

M = sym('M_%d_%d', [2 2], 'real');
syms s1 s2;
myExpr = M*[s1;s2];
matlabFunction(myExpr, 'Vars', {M,s1,s2}, 'file', 'myExprFunc.m');

Upvotes: 2

Related Questions