Assign values to n symbolic variables

조회 수: 4 (최근 30일)
David Pham
David Pham 2017년 11월 19일
답변: Sameer 2025년 6월 4일
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