Here's a good way to intersect a line with a grid of rectangles and get the lengths of each of the intersection segments: I used the line intersection from the pseudocode in the third answer from this link
% create some line form the equation y=mx+h m = 0.5; h = 0.2; x = -2:0.01:2; y = m*x+h; % create a grid on the range [-1,1] [X,Y] = meshgrid(linspace(-1,1,10),linspace(-1,1,10)); % create a quad mesh on this range fvc = surf2patch(X,Y,zeros(size(X))); % extract topology v = fvc.vertices(:,[1,2]); f = fvc.faces; % plot the grid and the line patch(fvc,'EdgeColor','g','FaceColor','w'); hold on; plot(x,y); % use line line intersection from the link DC = [f(:,[1,2]);f(:,[2,3]);f(:,[3,4]);f(:,[4,1])]; D = v(DC(:,1),:); C = v(DC(:,2),:); A = repmat([x(1),y(1)],size(DC,1),1); B = repmat([x(end),y(end)],size(DC,1),1); E = AB; F = DC; P = [-E(:,2),E(:,1)]; h = dot(AC,P,2)./dot(F,P,2); % calc intersections idx = (0<=h & h<=1); intersections = C(idx,:)+F(idx,:).*repmat(h(idx),1,2); intersections = uniquetol(intersections,1e-8,'ByRows',true); % sort by x axis values [~,ii] = sort(intersections(:,1)); intersections = intersections(ii,:); scatter(intersections(:,1),intersections(:,2)); % get segments lengths directions = diff(intersections); lengths = sqrt(sum(directions.^2,2)); directions = directions./repmat(sqrt(sum(directions.^2,2)),1,2); directions = directions.*repmat(lengths,1,2); quiver(intersections(1:end-1,1),intersections(1:end-1,2),directions(:,1),directions(:,2),'AutoScale','off','Color','k');
This is the result (the lengths of the arrows in the image are the lengths of the segment) 