Converting 2x1 Symbolic array to 2x1 Numeric matrix in Matlab

조회 수: 12 (최근 30일)
Mirroyal Ismayilov
Mirroyal Ismayilov 2019년 2월 10일
댓글: Steven Lord 2019년 2월 11일
I have a 2x1 symbolic array (2x1 sym):
C =
-(l1*(- l2*m2*sin(fi1 - fi2)*fidot2^2 + gr*m1*sin(fi1) + 2*gr*m2*sin(fi1)))/2
-(l2*m2*(l1*sin(fi1 - fi2)*fidot1^2 + gr*sin(fi2)))/2
here l1, l2, fi1, fi2, gr and etc. are symbolic variables.
I need to convert C symbolic array to 2x1 numeric matrix in a separate function tab in Matlab, where l1, l2, fi1, fi2 and etc. are given already.
I made a txt file with following commands:
smth=char(C);
fileID = fopen('C.txt','rt');
fprintf(fileID,'%s',smth);
fclose(fileID);
and it made a txt file with following content:
matrix([[-(l1*(gr*m1*sin(fi1) + 2*gr*m2*sin(fi1) -
fidot2^2*l2*m2*sin(fi1
- fi2)))/2], [-(l2*m2*(gr*sin(fi2) + fidot1^2*l1*sin(fi1 - fi2)))/2]])
But, I couldn't find a way to convert it back to numeric matrix.
What could be a way to convert symbolic matrix to numeric matrix?

채택된 답변

Steven Lord
Steven Lord 2019년 2월 10일
As madhan ravi said, use the subs function. Its whole purpose is to substitute values for symbolic variables into an expression. Alternately, if you want to convert the symbolic expression into a function file that you can call with values for the variables, use the matlabFunction function to generate that function file.
  댓글 수: 2
Mirroyal Ismayilov
Mirroyal Ismayilov 2019년 2월 10일
So, there is no way to convert back from txt file to matrix? I tried sym2double() and sym2num(), which didn't help me at all.
Steven Lord
Steven Lord 2019년 2월 11일
I don't believe the output of the char function on a symbolic expression is guaranteed to be in a form that you can evaluate to recreate the symbolic expression, at least not without going through MuPAD using the symengine function (which according to its documentation is not recommended as of release R2018b.) I believe you can define the symbolic variables and pass them into the function created using matlabFunction to do so, but if I wanted to store a symbolic expression for later use I'd save it in a MAT-file.
Perhaps if you tell us more about your use case, how you actually want to use this file, we can find a solution that will better satisfy your needs.

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

추가 답변 (0개)

Community Treasure Hunt

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

Start Hunting!

Translated by