2014-09-25 167 views
5

我想找到代數重建方法的權重矩陣。爲此我必須找到與網格的交線。我可以找到直線與直線的交點,但我必須存儲相交的線段網格編號。所以假設如果在網格中第一個平方不與網格相交,那麼將零置於權重矩陣的第一個元素上。 這裏代碼我試圖爲線相交:如何在matlab中得到直線矩形相交線段

ak = 3:6 
aka = 3:6 
x = zeros(size(aka)) 
y = zeros(size(ak)) 
for k = 1:length(ak) 
    line([ak(1) ak(end)], [aka(k) aka(k)],'color','r') 
end 

% Vertical grid 
for k = 1:length(aka) 
    line([ak(k) ak(k)], [aka(1) aka(end)],'color','r') 
end 
hold on; 
X =[0 15.5] 
Y = [2.5 8.5] 
m = (Y(2)-Y(1))/(X(2)-X(1)) ; 
c = 2.5 ; 
plot(X,Y) 
axis([0 10 0 10]) 
axis square 
% plotting y intercept 
for i = 1:4 
    y(i) = m * ak(i) + c 
    if y(i)<2 || y(i)>6 
     y(i) = 0 
    end 
end 
% plotting x intercept 
for i = 1:4 
    x(i) = (y(i) - c)/m 
    if x(i)<2 || x(i)>6 
     x(i) = 0 
    end 
end 
z = [x' y'] 

問題的說明:

我有一條線,由參數m, h,其中y = m*x + h此線變爲在網格定義(即像素)。對於網格的每個正方形(a, b)(即方形[a, a+1]x[b, b+1]),我想確定,如果給定的線是否穿過此方塊,如果是,則在方塊中的線段的長度是多少爲。這樣我就可以構造代數重構方法所必需的權重矩陣。

+0

我不知道你需要什麼幫助。你的代碼繪製了一個線條和一個gridsize 1從3到6的網格。並返回在3,4,5和6的y值。你想要什麼作爲最終結果,什麼是確切的問題? – 2014-09-25 08:42:28

+1

@TheMinion我有一條線,由參數m,h定義,其中 y = m * x + h 這條線穿過網格(即像素)。對於網格的每個正方形(a,b)(即正方形[a,a + 1] x [b,b + 1]),我想確定給定的直線是否穿過這個正方形,如果是,廣場中的分段的長度是多少? 這樣我就可以構造代數重建方法所必需的權重矩陣。 – 2014-09-25 13:00:22

+0

@ParthPatel考慮將問題的標題更改爲「如何在matlab中獲取線矩形相交線段」。我在下面回答你的問題,並舉例說明如何去做。 – DontCareBear 2015-09-12 01:02:15

回答

1

下面是相交的矩形的網格並得到各交叉段的長度的線的好方法:我用交線從僞碼中的第三個答案從這個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 = A-B; 
F = D-C; 
P = [-E(:,2),E(:,1)]; 
h = dot(A-C,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'); 

這是結果(圖像中箭頭的長度是段長度)enter image description here