简体   繁体   中英

How to go from a symbolic expression to a vector in MATLAB

I am working on a function that will generate polynomial interpolants for a given set of ordered pairs. You currently input the indexes of the node points in one vector, and the values of the function to be interpolated in a second vector. I then generate a symbolic expression for the Lagrange polynomial that interpolates that set of points. I would like to be able to go from this symbolic form to a vector form for comparison with test functions and such. That is, I have something that generates some polynomial P(x) in terms of some symbolic variable x. I would like to then sample this polynomial to a vector, and get values for the polynomial over (for example) linspace(-1,1,1000). If this is possible, how do I do it?

I guess I'll include the code that I have so far:

function l_poly = lpoly(x,f)
%   Returns the polynomial interpolant as computed by lagrange's formula
syms a
n=size(x,2);
l_poly_vec = 1;
l_poly=0;
for k=1:n,
    for l=1:n,
        if (k ~= l)
            l_poly_vec=l_poly_vec*(a-x(l))/(x(k)-x(l));
        end
    end
    l_poly=l_poly+f(k)*l_poly_vec;
    l_poly_vec = 1;
end

I plan on adding a third (or possibly fourth) input depending on how I can solve this issue. I'm guessing I would just need the length of the vector I want to sample to and the endpoints.

If I understand you correctly, you've constructed a Lagrange interpolating polynomial using the symbolic toolbox and now wish to evaluate it over a vector of values. One way to do this is to use the function sym2poly to extract the coefficients of the symbolic polynomial, and then use polyval to evaluate it. Alternatively, you could use matlabFunction to convert your symbolic expression into a regular Matlab function; or use subs to substitute in a numeric value for 'x'.

However, you would probably be better off avoiding the symbolic toolbox altogether and directly constructing the coefficients of the Lagrange interpolating polynomial, or, better yet, use a different interpolation scheme altogether. The function interp1 might be a good place to start.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM