0
votes

I am trying to numerically simulate a system using ODE45. I cannot seem to figure out why i'm getting the following error:

Error using vertcat Dimensions of matrices being concatenated are not consistent.

[t,x] = ode45(@NL_hw3c, [0,20], [1, 2, 3]);

function sys = NL_hw3c(t,x)
sys = [x(2)+ x(1)^2;
       x(3)+log10(x(2)^2 + 1);
       -3*x(1)-5*x(2)-3*x(3)+4*cos(t)-5*x(1)^2 -3*log10(x(2)^2 + 1) -6*x(1)*x(2) -6*x(1)^3 -(2*x(2)*(x(3)+ log10(x(2)^2 + 1)))/((x(2)^2 + 1)*log(10)) -2*x(1)*x(3) -2*x(1)*log10(x(2)^2 + 1) -2*x(2)^2 -8*x(1)^2*x(2) -6*x(1)^4];
end

Googled and couldn't find a similar solution. Any help would be appreciated. Thanks

1

1 Answers

1
votes

I had to separate each of the variables in your array for it to work:

 function s = NL_hw3c(t,x)
    s1 = x(2)+ x(1)^2;
    s2 = x(3)+log10(x(2)^2 + 1);
    s3 = -3*x(1)-5*x(2)-3*x(3)+4*cos(t)-5*x(1)^2 -3*log10(x(2)^2 + 1) -6*x(1)*x(2) -6*x(1)^3 -(2*x(2)*(x(3)+ log10(x(2)^2 + 1)))/((x(2)^2 + 1)*log(10)) -2*x(1)*x(3) -2*x(1)*log10(x(2)^2 + 1) -2*x(2)^2 -8*x(1)^2*x(2) -6*x(1)^4;
    s = [s1;s2;s3];
 end

I got the following output:

 t =

     0
0.0018
0.0037
0.0055
0.0074
0.0166
...
...
19.7647
19.8431
19.9216
20.0000

x =

 1.0000    2.0000    3.0000
 1.0055    2.0067    2.8493
 1.0111    2.0131    2.6987
 1.0167    2.0192    2.5481
 1.0224    2.0251    2.3975
 ...
 ...
 0.7926   -0.0187   -1.7587
 0.8380   -0.1567   -1.7624
 0.8781   -0.2928   -1.7534
 0.9129   -0.4253   -1.7299

The reason why your function didn't work was because in the last value of your array, the spaces between each part of the expression are interpreted as going into a separate column. Essentially, the first two rows of your matrix consist of 1 element and if you use the last expression exactly as it is, you would be trying to place 9 elements in the last row. I'm assuming you want a 3 x 1 matrix and the last element would thus violate the size of this matrix that you want to create and this is why it's giving you an error.

I'm assuming you want the last value as an entire expression, so to do this you will need to place this as a separate expression then place it into your array.

To make the code more readable, I've placed all of the entries as separate variables before making the array.