MATLAB: How to get the coefficient of this symbolic expression

coefficient of symbolic variable

This is my code
ti=0; tf=2;
h=0.5;
tt=ti:h:tf+h;
i=2;
syms q(t) p(t) d(t) g(t) y(t)
q(t)=1;
p(t)=t;
d(t)=0;
g(t)=2-abs(1-t);
aa=q(t)*(y(i+1)-2*y(i)+y(i-1))/h^2+p(tt(i))*(y(i+1)-y(i-1))/(2*h);
this is result
aa =
(7*y(1))/2 – 8*y(2) + (9*y(3))/2
I just want to get the coefficient of y(1),y(2) and y(3)
as [7/2 -8 9/2]

Best Answer

Try this. C vector contains the coefficient
ti=0; tf=2;
h=0.5;
tt=ti:h:tf+h;
i=2;
syms q(t) p(t) d(t) g(t) y(t)
q(t)=1;
p(t)=t;
d(t)=0;
g(t)=2-abs(1-t);
aa=q(t)*(y(i+1)-2*y(i)+y(i-1))/h^2+p(tt(i))*(y(i+1)-y(i-1))/(2*h);
syms x
C = zeros(1,3);
for i=1:3
temp = coeffs(subs(aa,y(i),x));
C(i) = temp(2);
end