How do I turn my function into a column vector?

7 次查看(过去 30 天)
I'm trying to solve a second-order differential equation using matlab, but for some reason I keep getting the error message that my function should be a column vector.
I'm calling the function (tryagain) from the following script (wilyourunnow):
clear all %Remove stray stuff
ht = linspace(0,10,1001);
h = sin(ht);
%This is based on the instructions as given in the help browser on the page
%for ode45; tab ODE with Time-Dependent Terms
[t,x] = ode45(@(t,x)'tryagain', (0:0.01:10), [0 1]);
plot(t,x)
And this is the function:
function dxdt = tryagain(t,x,ht,h)
h=interp1(ht,h,t);
dxdt = zeros(2, 1);
dxdt(1)= x(2);
dxdt(2) = -x.^2 + x + h;
When I try to run the script, I get the following error:
>> wilyourunnow
Error using odearguments (line 93)
@(T,X)'TRYAGAIN' must return a column vector.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);
Error in wilyourunnow (line 10)
[t,x] = ode45(@(t,x)'tryagain', (0:0.01:10), [0 1]);
I've already tried transposing the vector with these two commands (separately)
dxdt = transpose(dxdt)
dxdt = dxdt(:)

采纳的回答

madhan ravi
madhan ravi 2019-1-13
编辑:madhan ravi 2019-1-13
ht = linspace(0,10,1001);
h = sin(ht);
%This is based on the instructions as given in the help browser on the page
%for ode45; tab ODE with Time-Dependent Terms
[t,x] = ode45(@(t,x) tryagain(t,x,ht,h), (0:0.01:10), [0 1]); % change to be noted
plot(t,x)
function dxdt = tryagain(t,x,ht,h)
h=interp1(ht,h,t);
dxdt = zeros(2, 1);
dxdt(1)= x(2);
dxdt(2) = -x(2).^2 + x(1) + h; % two x here one has to be x(1) and the other x(2) , you have to correct it according to your equation parameters
end
Gives:
  4 个评论
Wouter Meekes
Wouter Meekes 2019-1-13
I realised where it went wrong only after literally copy-pasting your code over my own. When trying to solve the problem myself, I'd tried transposing dxdt (once more after posting the question), but forgot that I input that line. Removing that worked, and now with x replaced by x(1) all is solved.
Thanks a lot!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Ordinary Differential Equations 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by