Maci0503
Maci0503

Reputation: 9

How can vector elements with indexing be used in a MATLAB symbolic expression?

I would like to create a MATLAB function with vector inputs. The problem is that the inputs of a function created by matlabFunction() has only scalar inputs.

x = sym('x',[2 1]);
y = sym('y',[2 1]);
f=x(1)+x(2)+y(1)+y(2);
matlabFunction(f,'file','testFunction.m');
matlabFunction(f,'file','testFunction.m','vars',[x,y]); % tried with different options but doesn't work

This is the result (with x1,x2,y1,y2 inputs instead of x,y):

function f = testFunction(x1,x2,y1,y2)
%TESTFUNCTION
%    F = TESTFUNCTION(X1,X2,Y1,Y2)

%    This function was generated by the Symbolic Math Toolbox version 8.2.
%    10-Apr-2019 21:28:40

f = x1+x2+y1+y2;

Is there a solution to this problem within MATLAB? Or do I need to write a program opening the file as txt and replacing the words...

Update: I managed to solve the problem. For me, the best solution is the odeToVectorField() function.

Manually it is more difficult to give vector inputs to a function created by matlabFunction(). One way is the following:

syms y;
f=str2sym('y(1)+y(2)');
matlabFunction(f,'File','fFunction','Vars',y);

With this method, you need to manipulate the equation as a string (which is possible but not practical...), then re-convert it to symbolic expression.

Upvotes: 0

Views: 298

Answers (1)

Karls
Karls

Reputation: 751

If you check the result of f=x(1)+x(2)+y(1)+y(2) you will see that it is also scalar. Do simple test:

x = sym('x',[2 1]);
y = sym('y',[2 1]);
f=x(1)+x(2)+y(1)+y(2);
disp(f)

The results is x1 + x2 + y1 + y2. So there's nothing wrong with your matlabFunction expression, it just save what you give. If you need it to be stored in the form x(1)+x(2)+y(1)+y(2) you need to rewrite your f expression so it will be stored in vector form, until passing it to matlabFunction. Or alternatively you can create your file structure manualy using fprintf, look docs.

Upvotes: 0

Related Questions