How do I create a MATLAB function from some symbolic variables and a structure of symbolic variables?
4 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(1 个)
Ananya Tewari
2021-3-22
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'});
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Code Generation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!