How to convert a symbolic variable to an ordinary variable?

Hello. I have some code that looks like this (it's not that simple but the problem can be reduced to the following lines):
syms x y real;
A = [x y; 1 2];
for i = 1:10
x = i;
y = 2;
B = subs(A) % could also be: B=eval(A)
end
Is there a way i can make x and y ordinary variables again? Eval and Subs are too slow and consume 95% of runtime.
I use symbolic variables because in my code I get A by differentiating some expressions. After that A doesn't change anymore and I only want to evaluate A for different values of x and y.

 채택된 답변

Walter Roberson
Walter Roberson 2012년 7월 8일
syms x y real;
A = [x y; 1 2];
Afun = matlabFunction(A, 'vars', [x, y]);
for i = 1 : 10
B = Afun(i, 2);
end

댓글 수: 3

used your code
>> syms x y real;
A = [x y; 1 2];
Afun = matlabFunction(A, 'vars', [x, y]);
for i = 1 : 10
B = Afun(i, 2);
end
>> x=5
x =
5
>> syms x y real;
A = [x y; 1 2];
Afun = matlabFunction(A, 'vars', [x, y]);
for i = 1 : 10
B = Afun(i, 2);
end
>> A
A =
[ x, y]
[ 1, 2]
but its not updating the value
The poster asked, "I only want to evaluate A for different values of x and y". Nothing was said about updating the values of x, y, or A.
If you were using non-symbolic variables and created A = [x y; 1 2] and were later to change x or y, it would be inconsistent with the rest of MATLAB to expect the value of A to be updated. Use of a variable in an expression is always use of the value of the variable as of the time the expression is evaluated, and later changes to the variable do not affect the calculated expression. It is therefore correct and appropriate that A does not change as a result of the loop.
Also note that
x = 5;
syms x
is, by definition of syms(), equivalent to
x = 5;
x = sym('x');
and that this second assignment overwrites the first assignment. When you have a "syms" command, any referenced name loses its former value (but not always any assumptions that might have been placed on it.)
Thanks to both of you for helping me. matlabFunction is exactly what I was looking for. I tested it and it runs seven times faster now.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by