Error using sum function in function handle
古いコメントを表示
Hi everyone,
Using the following code, I get a matrix dimension error. This is caused only shen using sum inside the function.
% Data
y = [0.85 0.90]'; % Measurements array m x 1
m = length(y);
% Function
L = @(m_x,s_x) (1./s_x.^m).*exp(-0.5.*sum(((y - m_x)./s_x).^2));
% Visualization:
figure
fcontour(L,[0.6 1.4 0.05 0.15])
If I write the function analytically there is no problem.
L = @(m_x,s_x) (1./s_x.^m).*exp(-0.5.*(((y(1) - m_x)./s_x).^2 + ((y(2) - m_x)./s_x).^2));
Can anyone help me solve this issue?
7 件のコメント
mike Croucher
2021 年 2 月 11 日
The version with sum in it works perfectly for me using MATLAB 2020b. Which version of MATLAB are you using?
DIMITRIS GEORGIADIS
2021 年 2 月 11 日
dpb
2021 年 2 月 11 日
The above relies on implicit expansion -- it also will run on R2019b but fails on R2017b--
>> fcontour(L,[0.6 1.4 0.05 0.15])
Warning: Error updating FunctionContour.
Matrix dimensions must agree.
>>
fcountour internally expands the ranges -- observe what happens with
>> [X,Y]=meshgrid([0.6:0.2:1.4].',[0.05:0.05:0.15].');
>> L(X,Y)
Matrix dimensions must agree.
Error in @(m_x,s_x)(1./s_x.^m).*exp(-0.5.*sum(((y-m_x)./s_x).^2))
>>
Looking at the internals of L where y is only a 2-vector...
>> sum(((y - Y)./X))
Matrix dimensions must agree.
>>
The doc for fcontour notes "The function must accept two matrix input arguments and return a matrix output argument of the same size"
DIMITRIS GEORGIADIS
2021 年 2 月 11 日
dpb
2021 年 2 月 11 日
The problem is you've buried y inside the function definition L which is only a 2-vector whereas fcontour is trying to evaluate the function over a different set of variables if different length.
We don't know what y should be to be commensurate with the code; only you know what the real problem is.
I didn't have time to delve into just how the revised automagic expansion did the behind-the-scenes-magic that occurs after R2019b that was not present before; it often can give unexpected results or mask other problems like here.
You'll have to dig in and figure out just what the function is supposed to be doing when only have two elements for y
DIMITRIS GEORGIADIS
2021 年 2 月 11 日
DIMITRIS GEORGIADIS
2021 年 2 月 14 日
回答 (1 件)
Steven Lord
2021 年 2 月 11 日
0 投票
I suspect you have a variable named sum in your workspace when the anonymous function is created. If I'm correct the use of the identifier sum in L will be interpreted as an attempt to index into that variable not as a call to the sum function. Rename that variable.
カテゴリ
ヘルプ センター および File Exchange で Lighting, Transparency, and Shading についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!