12/22/2006

12.3 數值梯度gradient

12.3數值梯度gradient

一具有二自變數之函數F(x,y,z),其梯度之定義為:

▽F = (dF/dx)i +(dF/dy)j +(dF/dz)k

其計算之指令格式如下:

FX = gradient(F)
[FX,FY] = gradient(F)
[Fx,Fy,Fz,...] = gradient(F)
[...] = gradient(F,h)
[...] = gradient(F,h1,h2,...)

其中F為函數向量,切分後之間隔預設值為1,亦即h=1;若函數之變數增多,則h之值可因變數之不同另外設值。例如,h1可能屬於第一變數之區間;h2為第二變數之區間,而左邊之輸出值則依x,y,z之分量。


例一:



v=-2:0.2:2;
[x,y]=meshgrid(v);
z=x.*exp(-x.^2-y.^2);
[px,py]=gradient(z,.2,.2);
contour(z),hold on, quiver(px,py), hold off




例二:


設有一向量F由魔術矩陣及巴斯上矩陣組成,其內容為:

>> F(:,:,1) = magic(3); F(:,:,2) = pascal(3);
>> F

F(:,:,1) =

8 1 6
3 5 7
4 9 2


F(:,:,2) =

1 1 1
1 2 3
1 3 6

取其梯度值,即▽F,設dx=1,dy=1,dz=1。則


>> gradient(F)

ans(:,:,1) =

-7 -1 5
2 2 2
5 -1 -7


ans(:,:,2) =

0 0 0
1.0000 1.0000 1.0000
2.0000 2.5000 3.0000


若間矩不同,即設dx=0.1,dy=0.1,dz=0.1。則▽F為


>> [PX,PY,PZ] = gradient(F,0.1,0.2,0.3)

PX(:,:,1) =

-70.0000 -10.0000 50.0000
20.0000 20.0000 20.0000
50.0000 -10.0000 -70.0000


PX(:,:,2) =

0 0 0
10.0000 10.0000 10.0000
20.0000 25.0000 30.0000


PY(:,:,1) =

-25.0000 20.0000 5.0000
-10.0000 20.0000 -10.0000
5.0000 20.0000 -25.0000


PY(:,:,2) =

0 5.0000 10.0000
0 5.0000 12.5000
0 5.0000 15.0000


PZ(:,:,1) =

-23.3333 0 -16.6667
-6.6667 -10.0000 -13.3333
-10.0000 -20.0000 13.3333


PZ(:,:,2) =

-23.3333 0 -16.6667
-6.6667 -10.0000 -13.3333
-10.0000 -20.0000 13.3333