
how to correctly use the function "subs"
Show older comments
Hi there,
I am using subs to replace some symbols in a symbolic expression Jacobian_mtx_1. The symbols that I want to be replaced are A, B and C, which are a 6*1 symbolic vector, a symbolic scalar, and a 2*1 symbolic vector, respectively. I write the code:
Jacobian_mtx_1 = subs( Jacobian_mtx_1 , { A , B , C } , { A_val ,B_val , C_val } ) ;
where A_val is a 6*1 vector containing 6 function calls, B_val is a numeric scalar, and C_val is a 2*1 numeric vector.
However, the software reminds me that
Errors using sym/subs
Entries in second argument must be scalar.
Could anyone tell me how to resolve this issue?
Many thanks!
3 Comments
Umar
on 24 Jul 2024
Hi Tony,
When using the subs function in MATLAB to substitute symbols in a symbolic expression, the replacement values must be scalar. In your case, A_val is a 61 vector, B_val is a numeric scalar, and C_val is a 21 numeric vector, which is causing the error. To resolve this issue, you need to ensure that the replacement values are scalar. One approach is to replace each element of the vector with the corresponding element in the replacement vector. Here's how you can modify your code to achieve this:
% Define symbolic vectors and scalars
syms A B C
A_val = sym('A_val', [6, 1]);
B_val = sym('B_val');
C_val = sym('C_val', [2, 1]);
% Define the symbolic expression Jacobian_mtx_1
Jacobian_mtx_1 = A + B + C; % Example expression
% Perform substitution with scalar values
for i = 1:numel(A)
Jacobian_mtx_1 = subs(Jacobian_mtx_1, A(i), A_val(i));
end
Jacobian_mtx_1 = subs(Jacobian_mtx_1, B, B_val);
for i = 1:numel(C)
Jacobian_mtx_1 = subs(Jacobian_mtx_1, C(i), C_val(i));
end
So, in the above modified code snippet, I iterate over each element of the symbolic vectors A and C to perform individual substitutions with the corresponding elements in A_val and C_val, respectively. For the scalar symbol B, a direct substitution is made with B_val. By ensuring that the replacement values are scalar or by individually substituting elements of vectors, you can resolve the error and successfully substitute symbols in your symbolic expression. I hope this answers your question.
Tony Cheng
on 24 Jul 2024
Umar
on 24 Jul 2024
No problem, Tony, glad to help you out. Please let us know if you have any further questions.
Accepted Answer
More Answers (0)
Categories
Find more on Operations on Strings 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!