MATLAB Answers


The CLASS function must be called from a class constructor.

Asked by Kristian Jørgensen on 5 Feb 2013
Latest activity Commented on by hossein
on 24 Jun 2017

I'm currently working on a project involving some automatic differentiation, and was presented an example code to such an approach. My problems really boil down to me never working with OOD in Matlab before and it seems really overwhelming. The first part of the code looks like this, fairly straight forward. The problem is it won't run past the last line.

function ad = autodiff(val, der)
% A naive autodiff constructor.
ad.val = val;
if nargin == 1
    der = 0.0;
if strcmp(der,'variable')
    der = 1.0;
ad.der = der;
ad = class(ad, 'autodiff');

I get the error 'The CLASS function must be called from a class constructor', which I do not know how to deal with. How do I create custom classes and then call upon them later?

thanks in advance, Kristian


Did you have this file in a directory named '@autodiff', and is the directory that the @autodiff folder is in on the MATLAB path?

would you please explain more about the directory and @autodiff folder

Log in to comment.

1 Answer

Answer by Cedric Wannaz
on 5 Feb 2013
Edited by Cedric Wannaz
on 5 Feb 2013
 Accepted Answer

If you want to learn OOP in MATLAB, have a look at this document: MATLAB Object-Oriented Programming.

Basically, you want to create autodiff.m with a structure that will look like

 classdef autodiff
       function self = autodiff(val, der)    % Constructor.
          self.val = val;
          if nargin == 1,  self.der = 0.0;  end
          if strcmp(der,'variable'),  self.der = 1.0;  end
       function self = aMethod(self, ...)


Thank you so much. Really helped me out, and I'll be sure to check out your link. Appreciate it.

Log in to comment.

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!