4 views (last 30 days)

Show older comments

I want to call odefunction from classdef, but I don't know the way.

classdef plactice

properties

L = 1;

m = 1;

g = 9.8;

Tspan = linspace(0,2,20);

theta_ic = [0;0];

b = 0.01

u = randi([10 25],1,1);

end

methods

function [dtheta_dt] = ode_function(t, theta,g,L,u,b)

theta1 = theta(1);

theta2 = theta(2);

dtheta1_dt = theta2;

dtheta2_dt =-(g/L)*(theta1)-b*(theta2)-u;

dtheta_dt = [dtheta1_dt; dtheta2_dt];

end

end

end

The class may be written incorrectly.Is it written correctly?

please someone tell me.

Check the call to the function'ode_function' for incorrect argument data types or missing arguments.

Steven Lord
on 31 Jul 2021

With the way you've written this at least one of the inputs to ode_function must be a plactice object. ode45 won't call your function with either t or y a plactice object.

In addition, I suspect you expect that because the ode_function method has additional input arguments beyond the second required one whose names match the properties of your object that MATLAB will "automatically" pass those property values into your ode_function. That is not the case.

You can do this approach using Constant properties and a Static method. You would call it like:

sol = ode45(@plactice.ode_function, plactice.Tspan, plactice.theta_ic)

Here is the updated definition of plactice.

classdef plactice

properties(Constant)

L = 1;

m = 1;

g = 9.8;

Tspan = linspace(0,2,20);

theta_ic = [0;0];

b = 0.01

u = randi([10 25],1,1);

end

methods(Static)

function [dtheta_dt] = ode_function(t, theta)

% Define local variables to make the expression for dtheta2_dt

% shorter

g = plactice.g;

L = plactice.L;

u = plactice.u;

b = plactice.b;

theta1 = theta(1);

theta2 = theta(2);

dtheta1_dt = theta2;

dtheta2_dt =-(g/L)*(theta1)-b*(theta2)-u;

dtheta_dt = [dtheta1_dt; dtheta2_dt];

end

end

end

It would be possible to do this with a non-Static method and non-Constant properties, but you would have to pass an instance of your object into ode_function as an additional parameter. The ode45 documentation page includes a link to a page describing a few techniques for passing additional parameters into the ode function.

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

Start Hunting!