2

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?

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.