Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in matlab

I am having some trouble with matlab. I am working with b-splines. Sometimes I want to work with the actual spline, while other times I only want to use the so-called basis functions. Without diving into the theory of b-splines, the practical difference is that the when I want to work with the b-spline, I need an extra method and property. I want this property to be initialized by passing it in the constructor.

What I have so far (with most irrelevant methods and properties removed) hopefully roughly demonstrates the behavior that I want:

bsplinespace.m:

classdef bsplinespace < handle
    properties
        p % polynomial degree
    end

    methods
        function result = bsplinespace(p)
            result.p = p;
        end
    end
end

bspline.m:

classdef bspline < bsplinespace
    properties
        controlpoints
    end

    methods
        function result = bspline(p, controlpoints)
            result.controlpoints = controlpoints;
        end
        function result = getp(this)
            result = this.p;
        end
    end
end

However, in this scenario the bspline constructor calls the bsplinespace constructor without passing any arguments, causing it to crash:

Not enough input arguments.

Error in bsplinespace (line 8)
            result.p = p;

Error in bspline (line 7)
        function result = bspline(p, controlpoints)

To be more explicit, what I want is:

  • One class bsplinespace, which has a constructor which accepts one parameter p
  • A class bspline, which is the same, but has an extra property and method

Is there an elegant way to implement this?

like image 796
Ruben Avatar asked Jun 19 '26 01:06

Ruben


1 Answers

In your constructor method for bspline, you need to explicitly call the superclass constructor with input argument p:

function result = bspline(p, controlpoints)
    result@bsplinespace(p)
    result.controlpoints = controlpoints;
end

Otherwise MATLAB will call the superclass constructor with zero input arguments, and you'll get the error you're seeing.

It's a perfectly sensible design, and allows you to control the details of how arguments to the subclass constructor are passed through to the superclass constructor (or not, if you'd like to provide default arguments instead).

like image 192
Sam Roberts Avatar answered Jun 20 '26 19:06

Sam Roberts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!