(ODE45) Unable to perform assignment because the left and right sides have a different number of elements

2 views (last 30 days)
Hi guys. I have a problem about publishing the ODE45 function and plot.
%% Solving the system of non-linear differential equations
function dx = HW4_matlab(t,x)
dx = zeros(2,1);
dx(1) = exp(-x(1))-x(2)*t;
dx(2) = x(1)*t+cos(x(1)+x(2));
[t,x] = ode45(@HW4_matlab,[1,5],[10,2]);
plot(t,x(:,1),'-b',t,x(:,2),'--r')
When I am going to publish this code, an error shows up:
Unable to perform assignment because the left and right sides have a different number of elements.
Error in HW4_matlab (line 4)
dx(1) = exp(-x(1)) - x(2)*t;
How could I fix it?

Answers (2)

Star Strider
Star Strider on 1 Oct 2019
The code you posted runs for me with out error in R2019b.
The one change I made is to add an end statement to the function:
%% Solving the system of non-linear differential equations
function dx = HW4_matlab(t,x)
dx = zeros(2,1);
dx(1) = exp(-x(1))-x(2)*t;
dx(2) = x(1)*t+cos(x(1)+x(2));
end
[t,x] = ode45(@HW4_matlab,[1,5],[10,2]);
plot(t,x(:,1),'-b',t,x(:,2),'--r')
  3 Comments
Star Strider
Star Strider on 1 Oct 2019
Without more information, I have no idea what the problem could be that you are experiencing. As I mentioned, with that one change, your code runs for me withoout error. (I am running it inside a simple function that I use for some Answers problems.)

Sign in to comment.


James Tursa
James Tursa on 1 Oct 2019
Edited: James Tursa on 1 Oct 2019
It might be simpler to have separate files for this.
Put this code (and only this code) in a file called HW4_matlab.m
%% Solving the system of non-linear differential equations
function dx = HW4_matlab(t,x)
dx = zeros(2,1);
dx(1) = exp(-x(1))-x(2)*t;
dx(2) = x(1)*t+cos(x(1)+x(2));
end
And put this code in a separate file for calling that function
[t,x] = ode45(@HW4_matlab,[1,5],[10,2]);
plot(t,x(:,1),'-b',t,x(:,2),'--r')

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!