我正在尝试在MATLAB上制作著名的Split and merge算法以进行线提取。错误是 内存不足。可能的原因是程序内的无限递归。 task1> split中的错误(第88行) [alpha1,r1,idx1] = split(x,y,start,splitPos + start-2,threshold); 我知道这个问题已经提过,但是作为MATLAB的初学者,我不了解程序将如何进行无限递归以及如何避免它?谁能告诉我这个错误?代码如下。
clc;
close all;
clear all;
threshold = 50;
M = csvread('data.csv');
[m, n] = size(M);
lst = int64(n/6);
for i = 1: lst
index = 6*i-4;
rho(i) = M(1,index);
end
theta = zeros(1, lst);
max_angle = (7*pi)/6;
min_angle = -pi/6;
angle_diff = (max_angle - min_angle)/double(lst);
angle = max_angle;
for i = 1:16
theta(1,i) = angle;
angle = angle - angle_diff;
end
angle = min_angle;
for j = lst:-1:17
theta(1,j) = angle;
angle = angle + angle_diff;
end
%------------------------- Polar Coordiates Done----------------------
[x,y] = pol2cart(theta, rho);
x = -x;
plot(x,y,'o');
N = length(x);
[alpha, r, idx] = split(x,y,1, N,threshold);
function [alpha, r, idx] = split(x,y,start, ending, threshold)
N = ending - start + 1;
delX = x - (sum(x)/N);
delY = y - (sum(y)/N);
num = -2 * sum(delX.*delY);
denom = sum(delY.*delY - delX.*delX);
alpha = atan2(num, denom) / 2;
% compute parameter r by inserting the controid into the line equation and solve for r
r = ((sum(x)/N) * cos(alpha)) + ((sum(y)/N) * sin(alpha));
%-----------------------Line fit done---------------------------------
cosA = cos(alpha);
sinA = sin(alpha);
N = size(x,2);
d = zeros(N,1);
xcosA = x * cosA;
ysinA = y * sinA;
d = xcosA + ysinA - r;
%-------------------------- Distance calculated ----------------------
farOnPositiveSideB = d > threshold;
farOnNegativeSideB = d < -threshold;
neigborsFarAwayOnTheSameSideI = find((farOnPositiveSideB(1:N-1) & farOnPositiveSideB(2:N)) | (farOnNegativeSideB(1:N-1) & farOnNegativeSideB(2:N)));
if isempty(neigborsFarAwayOnTheSameSideI)
splitPos = -1;
else
absDPairSum = abs(d(neigborsFarAwayOnTheSameSideI)) + abs(d(neigborsFarAwayOnTheSameSideI+1));
[ans, splitPos] = max(absDPairSum);
splitPos = neigborsFarAwayOnTheSameSideI(splitPos);
if abs(d(splitPos)) <= abs(d(splitPos + 1)), splitPos = splitPos + 1; end
end
% ------------------------ Split Position calculated --------------------
if (splitPos ~= -1) % found a splitting point
[alpha1, r1, idx1] = split(x, y, start, splitPos+start-2, threshold);
[alpha2, r2, idx2] = split(x, y, splitPos+start-1, ending, threshold);
alpha = [alpha1; alpha2];
r = [r1; r2];
idx = [idx1; idx2];
else % no need to split
idx = [start, ending];
end
return
end