Home > Software engineering >  How to use RANSAC method to fit a line in Matlab
How to use RANSAC method to fit a line in Matlab

Time:11-16

I am using RANSAC to fit a line to my data. The data is 30X2 double, I have used MatLab example to write the code given below, but I am getting an error in my problem. I don't understand the error and unable to resolve it. The link to Matlab example is https://se.mathworks.com/help/vision/ref/ransac.html

load linedata
data = [xm,ym];
N = length(xm); % number of data points
sampleSize = 2; % number of points to sample per trial
maxDistance = 2; % max allowable distance for inliers
fitLineFcn = polyfit(xm,ym,1); % fit function using polyfit
evalLineFcn =@(model) sum(ym - polyval(fitLineFcn, xm).^2,2); % distance evaluation function
[modelRANSAC, inlierIdx] = ransac(data,fitLineFcn,evalLineFcn,sampleSize,maxDistance);

The error is as follows

Error using ransac Expected fitFun to be one of these types:

function_handle

Instead its type was double.

Error in ransac>parseInputs (line 202) validateattributes(fitFun, {'function_handle'}, {'scalar'}, mfilename, 'fitFun');

Error in ransac (line 148) [params, funcs] = parseInputs(data, fitFun, distFun, sampleSize, ...

CodePudding user response:

Lets read the error message and the documentation, as they tend to have all the information required to solve the issue!

Error using ransac Expected fitFun to be one of these types:

function_handle

Instead its type was double.

Hum, interesting. If you read the docs (which is always the first thing you should do) you see that fitFun is the second input. The error says its double, but it should be function_handle. This is easy to verify, indeed firLineFun is double!

But why? Well, lets read more documentation, right? polyfit says that it returns an array of the coefficient values, not a function_hanlde, so indeed everything the documentation says and the error says is clear about why you get the error.

Now, what do you want to do? It seems that you want to use polyfit as the function to fit with ransac. So we need to make it a function. According to the docs, fitFun has to be of the form fitFun(data), so we just do that, create a function_handle for this;

fitLineFcn=@(data)polyfit(data(:,1),data(:,2),1);

And magic! It works!

Lesson to learn: read the error text you provide, and the documentation1, all the information is there. In fact, I have never used ransac, its just reading the docs that led me to this answer.

1- In fact, programmers tend to reply with the now practically a meme: RTFM often, as it is always the first step on everything programming.

CodePudding user response:

maybe your data type is not single or double?

  • Related