使用匿名函数和内嵌函数处理多变量传递问题
生活随笔
收集整理的這篇文章主要介紹了
使用匿名函数和内嵌函数处理多变量传递问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題:有一個多變量函數f(abcx),現需要分別在a=a0b=b0c=c0和a=a1b=b1c=c1的條件下對f(abcx)進行某一操作。
此類問題常在數值積分時出現。
解決方案:
1. 使用全局變量
可在主調函數和被調函數中分別將a,b,c聲明為全局變量(global?a b c),這時f通過全局變量傳遞abc, 定義時可以只有一個參數x。
2. 使用anonymous function
3. 使用 nested function
下面舉例說明anonymous function和nested function的使用。
例:對任意二次多項式進行數此處顯然可以解析得到,此例使用anonymous
function做演示)
解:(1)使用匿名函數
編寫文件intpoly2.m
如下
執行:
保存該文件并將matlab切換至該文件目錄下,命令行輸入intpoly2(1,2,3), 便給出積分結果ans=4.33
實際上,上例也可以簡化成:
<span style="color: rgb(0, 0, 255);">function</span> y_int=intpoly2<span style="color: rgb(0, 136, 0);">(</span>a,b,c<span style="color: rgb(0, 136, 0);">)</span> y_int=quad<span style="color: rgb(0, 136, 0);">(</span>@<span style="color: rgb(0, 136, 0);">(</span>x<span style="color: rgb(0, 136, 0);">)</span><span style="color: rgb(0, 136, 0);">(</span>a.*x.^<span style="color: rgb(51, 51, 255);">2</span>+b.*x+c<span style="color: rgb(0, 136, 0);">)</span>, <span style="color: rgb(51, 51, 255);">0</span>,<span style="color: rgb(51, 51, 255);">1</span><span style="color: rgb(0, 136, 0);">)</span>; <span style="color: rgb(34, 139, 34);">%此處利用matlab內部函</span><span style="color: rgb(34, 139, 34);">%數quad(fun, x0,xt)進行積分,</span><span style="color: rgb(34, 139, 34);">%被積函數fun我們使用匿名函</span><span style="color: rgb(34, 139, 34);">%數@(x)(a.*x.^2+b.*x+c)以便</span><span style="color: rgb(34, 139, 34);">%將自變量限制為x. </span>(2)使用nested function
編寫函數保存為intnest.m, 內容如下
<span style="color: rgb(0, 0, 255);">function</span> y_int=intnest<span style="color: rgb(0, 136, 0);">(</span>a,b,c<span style="color: rgb(0, 136, 0);">)</span> y_int=quad<span style="color: rgb(0, 136, 0);">(</span>@poly2, <span style="color: rgb(51, 51, 255);">0</span>,<span style="color: rgb(51, 51, 255);">1</span><span style="color: rgb(0, 136, 0);">)</span>; <span style="color: rgb(34, 139, 34);">%此處利用matlab內部函</span><span style="color: rgb(34, 139, 34);">%數quad(fun, x0,xt)進行積分,</span><span style="color: rgb(34, 139, 34);">%被積函數fun我們使用內嵌函</span><span style="color: rgb(34, 139, 34);">%數poly2(x)的句柄@poly2 </span><span style="color: rgb(0, 0, 255);">function</span> y=poly2<span style="color: rgb(0, 136, 0);">(</span>x<span style="color: rgb(0, 136, 0);">)</span> <span style="color: rgb(34, 139, 34);">%此處定義一個內嵌函數 poly2( a,b,c,x) </span> y=a.*x.^<span style="color: rgb(51, 51, 255);">2</span>+b.*x+c; <span style="color: rgb(34, 139, 34);">%直接調用母函數中的變量a,b,c</span> <span style="color: rgb(0, 0, 255);">end</span> <span style="color: rgb(34, 139, 34);">% 結束內嵌函數poly2</span> <span style="color: rgb(0, 0, 255);">end</span> <span style="color: rgb(34, 139, 34);">% 結束母函數intpoly2</span>保存后執行,同樣效果。
可見nested
function只是將主調函數和被調函數封裝到了一起以共享主調函數的變量。
總結
以上是生活随笔為你收集整理的使用匿名函数和内嵌函数处理多变量传递问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: plot函数
- 下一篇: 自动调节图像的对比度 和改变图像的大小