How to convert a symbolic variable to an ordinary variable?
13 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponse acceptée
Walter Roberson
le 8 Juil 2012
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 commentaires
Walter Roberson
le 8 Juil 2012
Modifié(e) : Walter Roberson
le 8 Juil 2012
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.)
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Formula Manipulation and Simplification dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!