Search code examples
matlabanonymous-functionfunction-handle

Cell Array and function handle


Look at the below code:

for i=1:2
if i == 1
    F{i}= @(x) x(i)+x(i+1);
else
    F{i}= @(x) x(i-1)-x(i)+2;
end
end

I wanted to have stored in F something like F={@(x) x(1)+x(2);@(x) x(1)-x(2)+2;}. How should I edit my code to achieve this? Can anyone help me?


Solution

  • I think it's a displaying issue, rather than a functional issue.

    Doing this:

    for i = 1:2
        if i == 1
            F{i}= @(x) x(i)+x(i+1);
        else
            F{i}= @(x) x(i-1)-x(i)+2;
        end
    end
    

    actually gives the correct results:

    >> F{1}([1 2 3 4])
    ans =
         3    % == x(1)+x(2), i==1
    
    >> F{2}([1 2 3 4])
    ans =
         1    % == x(1)-x(2)+2, i==2
    

    But the functions are displayed "incorrectly":

    >> F
    F = 
        @(x)x(i)+x(i+1)    @(x)x(i-1)-x(i)+2
    

    If you want them to be displayed correctly as well, you'll have to get messy:

    for i=1:2
    
        if i == 1        
            F{i} = str2func(['@(x)x(' num2str(i) ')+x(' num2str(i+1) ')']);
        else        
            F{i} = str2func(['@(x)x(' num2str(i-1) ')-x(' num2str(i) ')+2']);
        end
    end
    

    Results:

    >> F
    F = 
        @(x)x(1)+x(2)    @(x)x(1)-x(2)+2