1/24/07

3.4 極座標轉換指令

除利用複數型式計算座標向量,在MATLAB中也有一個角度座標之轉換指令,可以將極座標系之向量轉化為直角座標:

[X,Y] = pol2cart(THETA,RHO)
[X,Y,Z] = pol2cart(THETA,RHO,Z) ----------------(3.15)

在極座標中,通常有徑向位移與夾角,類似複數指數在尤拉系的轉換。極座標之指令中,利用pol2cart可將角度(THETA,弧度)及位移量(RHO )轉換為直角座標之[X,Y]值。實際上其函數即含有X=RHO*cos(THETA),Y=RHO*sin(THETA) 之運算。




當然有了[x,y]值時亦可利用下式或cart2pol指令還原其徑向位移與角度:

theta = atan2(y,x)
rho = sqrt(x.^2 + y.^2)
[theta, rho]=cart2pol(x,y)---------------(3.16)

注意函數中有用到atan2(y,x)這個函數,在應用上此與atan(x)單參數有區別,atan2(y,x)具有雙參數,可以得到四個象限的位置,依X與Y項之值決定,其範圍為 -pi <= atan2(y,x) <= pi。 例如:X=-10,Y=5,則

>> theta1=atan(5/(-10))*180/pi
theta1 = -26.5651
>> theta1=atan2(5,-10)*180/pi
theta1 = 153.4349
>> cart2pol(-10,5)*180/pi
ans =
153.4349

顯然第一個答案僅給正負值的角度,而第二答案明顯告訴我們答案為第二象限。值得比較的是cart2pol反而可以得到考慮象限的答案,只是其輸入順序與atan2不同,必須注意。

座標轉換實例

範例2:利用上述三個位置向量r1、 r2、 r3分別為5(10°)、8(135°)、9(12°),求其直角座標?

function [rp,thetap]=Xresult(theta,rho)
% Find the resultants from connecting
% vectors in forms of rho(theta)
% theta in degrees
% Example: [rp, thetap]=Xresult([30 40 60],[3 4 5])
d2g=pi/180; %轉換為弧度
format short
[x,y]=pol2cart(theta*d2g,rho); %將角座標換為垂直座標
rpvec=[0 0;cumsum([x',y'])]; %行矩陣之加總
[theta,rp]=cart2pol(rpvec(:,1),rpvec(:,2));
thetap=theta/d2g;
hold on;
for i=2:length(rpvec)
plot([0 rpvec(i,1)],[0 rpvec(i,2)],'r-')
text(rpvec(i,1),rpvec(i,2),...
[' ' num2str(rp(i),3) '/' num2str(thetap(i),3)])
end
plot(rpvec(:,1),rpvec(:,2),'b*-');
xlabel('X-axis')
ylabel('Y-axis')
title('Find Reultants of Vectors')
axis equal

執行例:向量長[3 4 5]公分,對應水平角度[30 40 60]°,求其合向量及累計向量。

>> [rp, thetap]=Xresult([30 40 60],[3 4 5])
rp =
0
3.0000
6.9739
11.7134
thetap =
0
30.0000
35.7161
45.8268




範例3:試用極座標轉換指令作一繪圓程式。
說明:Target程式係利用pol2cart指令將圓之半徑與角度轉換為直角座標,然後進行繪製粗細不等之同心圓。圓之外圍半徑及點數可以輸入設定,沒有輸入參數時,其預設值r=1,n=100。


function h=target0(r,n)
%Draw circles using pol2cart command
% r,n:radius and number of point in a circle.
% Example: h=target
if nargin<1, r=1; n=100; end
theta=linspace(0,360,n)/180*pi;
rr=linspace(0,r,10);
for k=2:10,
[x,y]=pol2cart(theta,rr(k));
h=line(x,y,'linewidth',11-k,'color',[1 k k]/10);
end
axis equal


執行target指令,沒有輸入參數,其結果如圖1.4。

>> target0
ans =
166.0016




圖3.4 同心圓的繪製

上述之同心圓問題若改成繪製同心圓時,具有動畫的氣氛,使同心圓能依序繪製,則上述程式內容可以修改如下:

function h=target1(r,n)
%Draw circles using pol2cart command
% r,n:radius and number of point in a circle.
% Example: h=target1
if nargin<1, r=1; n=100; end
theta=linspace(0,360,n)/180*pi;
rr=linspace(0,r,10);
h=line(0,0);
while 1
for k=2:10,
[x,y]=pol2cart(theta,rr(k));
set(h,'xdata',x,'ydata',y,'linewidth',11-k,...
'erasemode','xor','color',[1 k k]/10);
pause(1);
drawnow;
end
end
axis equal


同學們不妨存檔然後執行,看其變化如何。若要改變其顏色,則應如何修改才能獲得所要的結果?

No comments:

Post a Comment