0
votes

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.

1
Why do you need vector inputs? If you want to give inputs to that function as vectors, you can use my answer from this questionSardar Usama
Vector inputs are convenient when x is a long vector. I'm not sure how this cell array method works.Maci0503
I would like to use the MATLAB function in Simulink. Your solution only works for MATLAB function calls. In Simulink, I can use a wrapper function which has vector inputs and calls the main function with scalar inputs (the elements of the vectors). Sorry, I haven't mentioned Simulink. Your solution is simplier because in my wrapper function, I have to manually access the elements of the vector while the num2cell() function does it automatically. But num2cell() isn't supported in Simulink.Maci0503
This is the error message: <imgur.com/tB7VDN0> The code of the function: function y = fcn(u) ucell = num2cell(u); y = u; (There are 3 rows, I can't write the code into the comment properly.)Maci0503

1 Answers

0
votes

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.