Assign values to n symbolic variables

4 次查看(过去 30 天)
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

回答(1 个)

Sameer
Sameer 2025-6-4
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!

类别

Help CenterFile Exchange 中查找有关 Symbolic Math Toolbox 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by