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!