MATLAB: Symbolic variables product does not produce symbolic result (Symbolic for loop)

for loopsyms

Hello, I have a problem with making symbolic variables. I want to have symbolic variables by user input. For example, when there are 3 variables, I will have S1, S2, S3.
This is what i've done so far:
num_sp = 'Number of variables: ';
K = input(num_sp);
% I've tried this
for i=1:K
eval(sprintf('S%d = sym(''S%d'')', i,i))
end
% OR THIS (but not both)
for i=1:K
syms (['S', num2str(i)])
end
syms E
obj_fun = cost_eng *E
for i=1:K
% 1st Case
obj_fun = obj_fun + (cost_inv(i) * (sprintf('S%d', i))
% or 2nd Case
obj_fun = obj_fun + (cost_inv(i) * (['S', num2str(i)]) )
end
However both gives me the answer of:
[ 2*E + 332, 2*E + 198]
for K = 2.
I don't know how the length becomes 2, when what I want is something like this:
obj_fun = cost_eng * E + cost1 * S1 + cost2 * S2
I've tried checking each elements but both is are not 2×1 matrix.

Best Answer

Try:
Ssym = sym('S', [1 5])
Now work with the elements of Ssym.