Error using sum function in function handle
Mostra commenti meno recenti
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 Commenti
mike Croucher
il 11 Feb 2021
The version with sum in it works perfectly for me using MATLAB 2020b. Which version of MATLAB are you using?
DIMITRIS GEORGIADIS
il 11 Feb 2021
dpb
il 11 Feb 2021
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
il 11 Feb 2021
dpb
il 11 Feb 2021
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
il 11 Feb 2021
DIMITRIS GEORGIADIS
il 14 Feb 2021
Risposte (1)
Steven Lord
il 11 Feb 2021
0 voti
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.
1 Commento
DIMITRIS GEORGIADIS
il 11 Feb 2021
Categorie
Scopri di più su Lighting, Transparency, and Shading in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!