Using subs on list of symbols

2 visualizaciones (últimos 30 días)
Ori Kenig
Ori Kenig el 5 de Dic. de 2022
Comentada: Walter Roberson el 5 de Dic. de 2022
Hello,
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)};
end
for m = 1:M
y = y + sym_means(:,m)
end
subs(y,names,values)

Respuesta aceptada

Walter Roberson
Walter Roberson el 5 de Dic. de 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)
  3 comentarios
Walter Roberson
Walter Roberson el 5 de Dic. de 2022
subs() with three parameters has two forms:
subs(Expression, VariableNamesMatrix, ValuesMatrix)
subs(Expression, VariableNamesCell, ValuesCell)
in the matrix form, the VariableNamesMatrix can be any dimension and the ValuesMatrix must be the same dimension and either numeric or symbolic; each entry in VariableNamesMatrix is substituted with the corresponding value in ValuesMatrix. Exception: if VariableNamesMatrix only has a single name then ValuesMatrix can be non-scalar and the entire matrix is substituted for the name
In the cell form, each entry in the cell VariableNamesCell (which can be any dimension) must be a single symbol, and the ValuesCell must be the same dimension; each entry in VariableNamesCell is substituted with the corresponding value in ValuesCell. This form must be used if there are more than one variables to be substituted and any of the values to be substituted are non-scalar.
Walter Roberson
Walter Roberson el 5 de Dic. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Community Treasure Hunt

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

Start Hunting!

Translated by