Using subs on list of symbols

2 views (last 30 days)
I have an equation containing a large amount of symbols that I want to evaluate.
I create the symbols in a for loop and give them unique names.
After creating the equation I want to evaluate all said symbols but I am not sure what's the best way to do so.
A code explaining my question:
( actual_means is the means values, e.g [1,2,3]' )
y = sym('y',[1,p]) ;
names = {};
values = {};
for m = 1:M
name = sprintf('means%d_',m);
sym_means(:,m) = sym(name,[1,p]);
names(end+1) = {name};
values(end+1) = {actual_means(:,m)};
for m = 1:M
y = y + sym_means(:,m)

Accepted Answer

Walter Roberson
Walter Roberson on 5 Dec 2022
name = sprintf('means%d_',m);
sym_means(:,m) = sym(name,[1,p]);
When you sym() a name and give a size, you generate a vector (or array) of symbols, such as means3_1 means3_2 ...
names(end+1) = {name};
You are only storing putting the base name. There is no symbol with that base name such as means3_
It looks to me as if what you should be doing is not looping, and instead
sym_means = sym('means%d_%d', [M p]);
y = sum(sym_means, 2);
values = actual_means;
subs(y, sym_means, values)
Walter Roberson
Walter Roberson on 5 Dec 2022
sym_means = sym('means%d_%d', [2 3 2]);
y = sum(sym_means, 2)
y(:,:,1) = 
y(:,:,2) = 
values = randi([-9 9], 2, 3, 2)
values =
values(:,:,1) = -1 0 7 9 -6 0 values(:,:,2) = -3 -3 -8 9 4 4
subs(y, sym_means, values)
ans(:,:,1) = 
ans(:,:,2) = 
You can see here that it was not a problem that sym_means is a 3D array of variable names.

Sign in to comment.

More Answers (0)


Find more on Symbolic Math Toolbox in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!