Why does this happen? - In an assignment A(I) = B, the number of elements in B and I must be the same
3 views (last 30 days)
Show older comments
Hi all,
I'm writing some simple code to plot some differential equations and I'm getting the error I stated in the title and also this: "Error in ==> ModelingQ2hind at 5 dxdt(1) = k(1) * (x-3);".
This is my code:
function dxdt = ModelingQ2(t,x,k)
dxdt = zeros (2,1)
dxdt(1) = k(1) * (x-3);
dxdt(2) = (k(3)-2) * (x-3);
end
and my inputs where like this:
k(1) = 1; % k1
k(2) = 1.5; % k2
k(3) = 4; % S
[t,x] = ode45(@ModelingQ2,[0:0.1:10],[4:0.5:10],[],k);
size(t)
size(x)
plot(t,x)
I cannot figure out what the problem is.... k(1) is a scalar, so why is this happening? i would really appreciate some help!
0 Comments
Answers (3)
the cyclist
on 16 Oct 2011
The problem is not in the multiplication, which is fine. The problem is that the right-hand side resolves to a 13x1 vector, and you are trying to assign that to a single element on the left-hand side.
0 Comments
Naz
on 16 Oct 2011
Maybe, this will do:
function dxdt = ModelingQ2(t,x)
dxdt = zeros (size(x));
dxdt(1,:) = x-3; % your k(1)=1, so you can omit it
dxdt(2,:) = 2 * (x-3); % k(3)-2=2
end
You never use k(2). Then try to call the ode45 this way:
[t,x] = ode45(@ModelingQ2,[0:0.1:10],[4:0.5:10]);
where your time span is 0:0.1:10 and initial conditions are 4:0.5:10
0 Comments
Walter Roberson
on 16 Oct 2011
If you examine the ode45() documentation, you will see that the function you supply must be prepared to receive a scalar t and a column vector of x, and must return a column vector with one element for every input element in x.
Example 2 implies that x will have one value for each simultaneous differential equation.
You will also note that you cannot pass additional variables (e.g., k) to the solution function by listing the extra variables at the end of the ode45() parameter list. Instead, you must parametrize the anonymous function as described here
0 Comments
See Also
Categories
Find more on Ordinary Differential Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!