user5385917
user5385917

Reputation:

Matlab function doesn't return vector

This is a function used to evaluate a certain value f(x) showing diverse approximations in a vector y, in order to be compared. Input is a function f (either symbolic or function_handled), a vector of values n, and two values x0 and x.

g=sym(f);
p(1)=subs(g,x0);

k=1;

for i=1:size(n) %Every iteration is an entry of y
    while k<=n(i) %Recursive evaluation of the values
        g=diff(g);
        p(k+1)=subs(g,x0)/factorial(k-1);

        k=k+1;
    end

    y(i)=double(subs(p,x));
end

I want to approximate f(x) as a polynomial a+bx+cx^2+... in every entry, and the while loop calculates a, b, c..., but y turns out to be a value, not a vector. Furthermore, if I try to do

[y1 y2]=(function)

A too many output arguments error is displayed. Could you tell me why doesn't MATLAB understand y as a vector?

Upvotes: 0

Views: 281

Answers (2)

hosein azhdari
hosein azhdari

Reputation: 1

I think if you know how many elements y will have the best way is to define y as a zero vector and the give the values to it one by one or if you don't know expand the vector y every time(it's not a good idea due to time!) like y(i+1) = [y(i) sth];

Upvotes: 0

user1543042
user1543042

Reputation: 3440

This should do the trick. Although, I honestly can't understand your function as written. Where is the (x-x0) term?

function y = vctay(f, n, x, x0)
    g=sym(f);

    n = sort(n(:));
    p = zeros(max(n)+1,1);

    for i = 0:max(n)
        %This is like you had it p(i) = (1/i!) f^i (x0)
        p(i+1) = subs(g, x0) / factorial(i) ;

        %This is just to save on a derivative in case it's costly
        if (i == numel(p))
            break
        end

        %This is what you had
        g = diff(g);
    end

    y = arrayfun(@(j) dot(p(1:j+1), (x - x0).^(0:j)) , n ); %This is the secret sauce. It's the sum p_0 * (x - x0)^0 + p_1 (x - x0)^1 + ...

end

Upvotes: 1

Related Questions