Autogenerating fuctions from syms-Expression

조회 수: 1 (최근 30일)
metty
metty 2019년 7월 4일
댓글: metty 2019년 7월 16일
Suppose I have a symbolic expression in Matlab that contains a vector, for example:
syms v1;
syms v2;
vector(1) = sin(v1)+cos(v2);
vector(2) = 1-sin(v1);
Is there a easy way to automatically make a function out of only the variable "vector" that looks something like this?
function vector = myFunction(v1,v2)
vector(1) = sin(v1)+cos(v2);
vector(2) = 1-sin(v1);
end
Of course, it's pointless in this example. I only have a relatively large matrix with long entries instead of the vector.
It would save me a lot of typing.
  댓글 수: 1
metty
metty 2019년 7월 5일
This solved it for me:
delete temp.txt
diary temp.txt
for i= 1:length(vector)
X = sprintf('vector(%d)=',i);
disp(X)
vector(i)
end
diary off
%%
find_and_replace('temp.txt', '\n \nans =\n \n', ' ');
find_and_replace('temp.txt', '\n \n', ';\n \n');
With the "find_and_replace" script from here.

댓글을 달려면 로그인하십시오.

답변 (1개)

Chidvi Modala
Chidvi Modala 2019년 7월 16일
I understood that you wanted to create a function which can automatically create equations and store them in a variable ‘vector’.
The below code will help you out
function vector=myFunc
vector{1}=@(v1,v2)(sin(v1)+cos(v2));
vector{2}=@(v1)(1-sin(v1));
end
Use fsolve to solve the above equations.
  댓글 수: 1
metty
metty 2019년 7월 16일
My initial situation was not the function, but the vector with syms entries. In my specific case, a matrix. The individual terms in the matrix are very large, and it would take me a day to type them out.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Numeric Solvers에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by