How do I create a MATLAB function from some symbolic variables and a structure of symbolic variables?

3 visualizaciones (últimos 30 días)
Hi everyone, and thanks in advance for the replies.
My code start like this:
x = {'X','Y','vx','vy'};
syms(x)
x=cell2sym(x);
assume(x,'real')
mystruct.a = sym('a',[1,2],'real');
mystruct.b = sym('b',[1,2],'real');
M = [x(1),x(2);mystruct.a(1),mystruct.b(1)];
What I want is to generate in the current folder a .m function file like this:
function M = myfunction(x,mystruct)
X = x(1);
Y = x(2);
a1 = mystruct.a(1);
b1 = mystruct.b(1);
M = [X,Y;a1,b1];
end
namely, in which its inputs are exactly (x,mystruct) and not (X,Y,a1,b1).
I tried to use the "matlabFunction" command in this way:
matlabFunction(M,'file','myfunction','Vars',{x,mystruct},'output',{'M'});
but it doesn't work because 'Vars' does not accept a struct (like mystruct). Does anyone knows how to overcome this problem or can propose me other approaches?

Respuestas (1)

Ananya Tewari
Ananya Tewari el 22 de Mzo. de 2021
I understand that you want your inputs to be (x,mystruct) for 'Vars' field matlabFunction().
The 'vars' field of matlabFunction() only accepts character vector, 1-d cell array of character vector or array of symbolic variables. Structres are not accepted by the 'Vars' field.
Here is a workaround for the above given code:
Rather than using structure we can use array of symbolic variables
x = {'X','Y','vx','vy'};
syms(x)
x=cell2sym(x);
assume(x,'real')
% creating two sym variables rather than structure
a = sym('a',[1,2],'real');
b = sym('b',[1,2],'real');
% creating array for the sym variables
y = [a(1) b(1)];
M = [x(1),x(2);y(1),y(2)];
matlabFunction(M,'file','myfunction','Vars',{x, y},'output',{'M'});
  1 comentario
Manuel Coccia
Manuel Coccia el 24 de Mzo. de 2021
Thank for your reply.
Yes, I want to create a function with input x and mystruct.
Unfortunately, I cannot replace the structure mystruct with an array of symbolic variables, because this structure is utilized in many other parts of my code. Also a compromise solution like this:
y = [mystruct.a(1),mystruct.b(1)] % (*)
M = [x(1),x(2);y(1),y(2)];
matlabFunction(M,'file','myfunction','Vars',{x, y},'output',{'M'});
cannot be performed because mystruct is too big in my real code to do the step (*) manually.
So, since the matlabFunction() command has this limitation, do you know other approaches to solve the problem?
Thanks again.

Iniciar sesión para comentar.

Categorías

Más información sobre Code Generation en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by