Search code examples
matlabcell-arraydifferential-equations

Evaluate Equation in Cell Array, MATLAB


I have a cell array containing functions (with function handle) and I want to evaluate these inside a for-loop. I want to evaluate the differential equations: x1'= x2, x2' = ax2-bx1

My code is like this:

init = [0,0];
F = {@(x1,x2) x2,@(x1,x2)(a*x2-b*x1)};
X0 = init;

for i=1:10
   X = X0 + c*F(init(1),init(2));
   X0 = X;
   init[1] = {X(1)};
   init[2] = {X(2)};
end

The constants a,b and c are given.

I get the error:

Subscript indices must either be real positive integers or logicals.

Can someone help me with this?


Solution

  • First of all, there are two other problems with your code: c is not defined and you are trying to index into init with []-brackets, which will throw:

    Error: File: foo Line: 8 Column: 8
    Unbalanced or unexpected parenthesis or bracket. 
    

    The subscript error occurs because you are trying to access F(0,0) because init(1) and init(2) are 0. Remember that the way you declared F, it is a cell array:

    >> F = {@(x1,x2) x2,@(x1,x2)(a*x2-b*x1)};
    >> whos F
      Name      Size            Bytes  Class    Attributes
    
      F         1x2               288  cell  
    

    Hence, F(0,0) is illegal because indexes in matlab start with 1. Your functions reside in F{1} and F{2}.

    >> F{1}
    ans = 
        @(x1,x2)x2
    >> F{2}
    ans = 
        @(x1,x2)(a*x2-b*x1)
    >> f = F{1}
    f = 
        @(x1,x2)x2
    >> f(0,0)
    ans =
         0