我正在制作LogSumExp函式的曲面圖。此函式與max 類似,因為它采用一組數字并(大約)回傳這些數字的最大值;與max 不同, LogSumExp 函式是平滑的。為了理解 LogSumExp 函式,我希望看到它使用由兩個數字組成的輸入集繪制,用作曲面圖的 x 和 y 坐標。
以下代碼:
function lse = lse(x)
lse = log(sum(exp(x)));
end
fsurf(@(x,y) lse([x y]))
繪制圖形(成功!)但會產生以下警告訊息:
Warning: Function behaves unexpectedly on array inputs. To improve
performance, properly vectorize your function to return an output with
the same size and shape as the input arguments.
> In matlab.graphics.function.FunctionSurface>getFunction
In matlab.graphics.function/FunctionSurface/updateFunction
In matlab.graphics.function/FunctionSurface/set.Function
In matlab.graphics.function.FunctionSurface
In fsurf>singleFsurf (line 267)
In fsurf>@(f)singleFsurf(cax,{f},extraOpts,args) (line 233)
In fsurf>vectorizeFsurf (line 233)
In fsurf (line 206)
從 Internet 搜索和其他 StackOverflow 答案中,我了解到fsurf
嘗試將向量直接傳遞給函式以獲取向量,因為這比為每個 ( x, y ) 對呼叫一次函式產生更快的性能。
但是,根據定義,LogSumExp 函式將向量簡化為標量,因此我什至不確定是否可以對其進行向量化。
有沒有辦法矢量化 LogSumExp?如果沒有,有沒有辦法阻止警告資訊?
uj5u.com熱心網友回復:
考慮max
函式。它可以以兩種方式(或其變體)使用:
max(x, y)
x
計算和的元素最大值y
:>> max([10 20], [0 30]) ans = 10 30
max(x, [], n)
計算x
沿其維度的最大值n
:>> max([10 20; 0 30], [], 1) ans = 10 30
您已經lse
使用第一種方法定義了您的功能。但是,第二種更適合矢量化。要lse
使用第二種方法進行定義,請注意sum
也可以使用以下語法sum(x, n)
:
function lse = lse(x, n)
lse = log(sum(exp(x), n));
end
fsurf
然后可以將傳遞給的匿名函式定義為,使用將呼叫它的引數是矩陣(即維度)@(x,y) lse(cat(3, x, y), 3)
這一事實。因此,x
y
fsurf
2
fsurf(@(x,y) lse(cat(3, x, y), 3))
生成沒有警告的情節:
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/467369.html
上一篇:在MATLAB上著色3D圖