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

6 ビュー (過去 30 日間)
Kengchit Lam 2019 年 10 月 1 日
Commented: Kengchit Lam 2019 年 10 月 1 日
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?

#### 0 件のコメント

サインイン to comment.

### 件の回答 (2)

Star Strider 2019 年 10 月 1 日
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 件のコメント

Kengchit Lam 2019 年 10 月 1 日
After I added the end statement, there is another type of error:
%% 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')
Error using dbstatus
Error: File: /Users/kennylam/Desktop/CHEN 2001/HW4_matlab.m Line: 8 Column: 1
This statement is not inside any function.
(It follows the END that terminates the definition of the function "HW4_matlab".)
In addition, I am using R2019a
Star Strider 2019 年 10 月 1 日
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.)
Kengchit Lam 2019 年 10 月 1 日
Problem solved! Thank you!

サインイン to comment.

James Tursa 2019 年 10 月 1 日

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')

#### 1 件のコメント

Kengchit Lam 2019 年 10 月 1 日
Problem solved! Thank you James!

サインイン to comment.

サインイン してこの質問に回答します。

Translated by