Hi all, I am encountering a problem with vectorization and eval. So here is the code
syms a b c i
A = [a*i; b-i; c+i]
a = 10;
b = 2;
c = 3;
d = 4;
i = [1:3];
eval(A)
This would return a matrix as the following.
10 20 30
1 0 -1
4 5 6
What I want is the calculation being performed as the followings
- For A(1), eval will be performed by using i = i(1)
- For A(2), eval will be performed by using i = i(2)
- For A(3), eval will be performed by using i = i(3)
So the return would be
10 0 6
I'd like to do it in a way that uses vectorization. Because in my real application, the array is much larger and the symbolic equation is a lot more complicated. Using for and if might sacrifice the efficiency.
Thanks for the help.
Steph

 Réponse acceptée

Ameer Hamza
Ameer Hamza le 14 Mai 2018

0 votes

Secondly, what you are trying to do can be done correctly using for loop but since, but here is a simple solution using arrayfun,
syms a b c i
A = [a*i; b-i; c+i];
aa = 10;
bb = 2;
cc = 3;
dd = 4;
ii = 1:3;
vector = cell2mat(arrayfun(@(s, i_) double(subs(s, {a b c i}, {aa bb cc i_})), A, ii', 'UniformOutput', 0));
I renamed the variables because your original variables names were overwriting previous declarations.

6 commentaires

Stephen
Stephen le 15 Mai 2018
Thanks for the information.
Stephen
Stephen le 15 Mai 2018
In retrospect, I would like to ask isn't "subs" as slow as "eval"?
Walter Roberson
Walter Roberson le 15 Mai 2018
subs() is probably slower than eval, as subs() works in the symbolic engine and triggers symbolic computation.
Ameer Hamza
Ameer Hamza le 15 Mai 2018
But subs allow to do it more cleanly. In your original code, you were initializing a,b,c and d as sym initially and then replacing them with their numeric values. It will likely make your code more error-prone and decrease readability.
Stephen23
Stephen23 le 15 Mai 2018
Modifié(e) : Stephen23 le 15 Mai 2018
"In retrospect, I would like to ask isn't "subs" as slow as "eval"?"
That is not really the point: subs is simply the correct tool for substituting values into symbolic expressions. Take a look at the Symbolic Math Toolbox functionlist, and you will only find subs listed (and eval is nowhere to be seen). eval is really just the wrong tool to use.
Walter Roberson
Walter Roberson le 15 Mai 2018
The language produced by the Symbolic Toolbox is not quite the same as MATLAB. There are symbolic expressions that will produce the wrong answer or an error if you eval() then. subs() is the right thing to do for symbolic expressions.

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by