Assign values to n symbolic variables

4 views (last 30 days)
David Pham
David Pham on 19 Nov 2017
Answered: Sameer on 4 Jun 2025
I have symbolic variables that goes from 1 to a user assigned value 'n' (i.e. x1,x2,x3,...,xn). Is there any way I can assign a value to each of these symbolic variables? I have a matrix 's' of size (1,n) with the input values. Ideally, I want it to work something like this:
for i = 1:n
x(i) = s(i)
end

Answers (1)

Sameer
Sameer on 4 Jun 2025
You can assign values to a set of symbolic variables like "x1", "x2", ..., "xn" using symbolic toolbox. The best way is to create a symbolic vector and then substitute the values using the "subs" function.
Here’s how you can do it step-by-step:
syms x [1 n] % creates symbolic variables x1, x2, ..., xn as a vector
% Suppose s is your 1-by-n matrix of values
s = [value1, value2, ..., valuen]; % replace with your actual values
% Now substitute each xi with the corresponding value in s
expr = x; % or any symbolic expression involving x
expr_substituted = subs(expr, x, s);
% expr_substituted now has each xi replaced by s(i)
If you want to assign values individually (though not usually necessary), you could do:
for i = 1:n
assignin('base', sprintf('x%d', i), s(i))
end
But the preferred symbolic approach is using "subs".
Example:
n = 3;
syms x [1 n]
s = [10, 20, 30];
expr = x(1)^2 + x(2)*x(3);
expr_substituted = subs(expr, x, s);
disp(expr_substituted) % Output: 10^2 + 20*30 = 100 + 600 = 700
Hope this helps!

Categories

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

Products

Community Treasure Hunt

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

Start Hunting!