Stuart’s MATLAB Videos

Watch and Learn

Piecewise linear curve fitting 15

Posted by Doug Hull,

This week, I am getting back to my blogging roots and I want to highlight (and thank) John D’errico for a great file Exchange submission. That file is Shape Language Modeling.

Recently I had some very noisy data that I wanted to fit a curve to. The problem is there were different regions that were somewhat linear, but the overall data was far from linear. A spline or a polynomial did not capture the behavior in a global sense. What I wanted was the ability to fit a line to each region. SLM does that right out of the box.

I think it is very instructive to look at how this code was packaged up. There is a clearly labeled tutorial that was easy to scan looking for an example like what I wanted to do. All of the files have lots of comments. sometimes more comments that code I think. The files are named coherently so they make a nice package. These are all great things to make a package that other people can use.

15 CommentsOldest to Newest

Doug replied on : 2 of 15


Nice! I love it when I can learn about MATLAB functions that I did not know exist! It is a very large product, impossible to know it all!


owr replied on : 3 of 15

Nice pick Doug – did you have to specify how many linear segments there are in your data? If so, do you have to specify the location of the knots?


James replied on : 6 of 15

Yeah, code would have been nice – how can I learn this without an example to display some metacognitiion? Not trying to complain, but kind of lame.

Kevin replied on : 10 of 15

Hi Doug, great code. I was wondering if there was a way to specify a range for the interior knots. For example, if I have x-axis data ranging in value from 0 to 10, and I want 4 knots, the first at 0, the last at 10, and the middle 2 at or between 4 and 8. Is there a way to make this happen using your slm toolbox? The ‘interior knots’ just puts the knots at any number great than 0 or less than 10, I believe. Thanks!

Cheng replied on : 12 of 15

Hi there, in your example, how did you decide the number and the position of “knots” of your fitting curve?

Ahmad R replied on : 14 of 15

It is a nice code however it seems that it uses equally spaced “knot”‘s locations which is not ideal for many cases.

Ahmad R replied on : 15 of 15

Oops! I should correct my previous comment:

Here, we can freely define interior knots:
slmengine(x,y,’degree’,1,’knots’,4, ‘interiorknots’,’free’,’plot’,’on’);

Now I would say it’s a great piece of code!

Add A Comment

Your email address will not be published. Required fields are marked *

Preview: hide