Search code examples
matlabanonymous-functioncell-arrayfunction-handle

Linear transformation function handle


Assume I have the legendre polynomials in cell Array P as function handles. Now I use the linear transformation x = 2/3*t-1. Now I want to get a cell array Q which has the transformation function handle. So P = [1, @(x) x, 1/2*(3*x^2-1),...] to Q = [1,@(t) 2/3*t-1,...]

Thanks!


Solution

  • Assuming you have the Symbolic Toolbox, you can do it this way:

    1. Convert your cell array of anonymous functions to a cell array of strings
    2. Do the change of variable using subs. This produces symbolic objects as output.
    3. Convert from symbolic objects to anonymous functions using matlabFunction:

    Code:

    P = {@(x) 1, @(x) x, @(x) 1/2*(3*x^2-1)};        %// data 
    f = cellfun(@func2str, P, 'uniformoutput', 0);   %// step 1
    Q = arrayfun(@(k) matlabFunction(subs(f{k}(5:end), 'x', '2/3*t-1')), 1:numel(P),...
        'uniformoutput', 0);                         %// steps 2 and 3.
        %// Note that the "(5:end)" part is used for removing the initial "@(x)"
        %// from the string obtained from the function
    

    Result in this example:

    Q{1} =
        @()1.0
    Q{2} =
        @(t)t.*(2.0./3.0)-1.0
    Q{3} =
        @(t)(t.*(2.0./3.0)-1.0).^2.*(3.0./2.0)-1.0./2.0