Extracting coeffients and constants from a symbolic expression
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi. im rather new to symbolic toolbox. Following is my code.
clear all; close all; clc;
N=3; alphavec = sym('alpha',[1 N]); %N is a variable input by user
derv_alpha=[-2*alphavec(2)-3*alphavec(3)+2-alphavec(1), 4*alphavec(2)-alphavec(3)]; %my expression (an example with 2 expressions); This is the output from another line of code and hence I have no control over it
derv_alpha=simplify(derv_alpha) %simplified expression
Now I want to get the coefficint matrix with the constant terms
xx = symvar(derv_alpha); %get variables in the expression
Coef_matrix = zeros(numel(derv_alpha),numel(xx)); %coefficient matrix: rows=no of expressions. columns=no of variables
for j = 1 %i.e. first expression
[a,b] = coeffs(derv_alpha(j),xx);
Coef_matrix(j,ismember(xx,b)) = a(1:numel(xx)); % I have got the coeff for alpha's
% Coef_matrix(j,ismember(xx,b)) = a % if I put this it gives me an
% error Subscripted assignment dimension mismatch.
end
for j = 2
[a,b] = coeffs(derv_alpha(j),xx);
Coef_matrix(j,ismember(xx,b)) = a; % I get coeff for alpha's
% Coef_matrix(j,ismember(xx,b)) = a(1:numel(xx)); % if I put this, I
% get only 2 coeff instead of 3. The '0' is missing in alpha1
end
Question1: Now I need to combine these j=1 and j=2 into one loop.How can I do this? i.e. j=1:numel(derv_alpha)
Question2: How can I also get the constant into this matrix? If the constant is zero, I want to capture that also. So that the final one looks like this:
Answer=[-1 -2 -3 2; 0 4 -1 0]
I searched and it says "you can also create symbolic constants with the sym" but in my case, the constant term varies every time
Thanks a million
0 commentaires
Réponses (0)
Voir également
Catégories
En savoir plus sur Numbers and Precision dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!