Need help running simple equation over vector of data?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Michael Ziedalski
le 1 Fév 2018
Commenté : Star Strider
le 3 Fév 2018
So, I am new to Matlab and would appreciate all the help I can get. Recently, I coded an anonymous function (meant to represent a bivariate normal distribution) and was able to output a vector of results if I fed the x values to it (representing both of the means and st. deviations). This was my code
mu = [1;5]
sigma = [.5,0;0,.1]
data = mvnrnd(mu,sigma,100);
data1 = data(:,1);
data2 = data(:,2);
fun = @(x)(1/(2*pi*x(2)*x(4)*sqrt(1-.533^2)))*exp((-1/(2-2*.533^2))*((data1-x(1)).^2./(x(3)^2)+(data2-x(2)).^2./(x(4)^2)-(2*.533*(data1-x(1)).*(data2-x(2)))./(x(3)*x(4))))
fun([1,2,3,4]) %This outputs my answers.
The last line correctly gives me a 2x100 vector of results, since I gave 100 data values. But now I want to simplify this code b/c it was giving me issues elsewhere. I wanted to include data itself as a variable of sorts, and get the same answer. But only 1 answer gets outputted from the below code and that is puzzling.
fun = @(x, data)(1/(2*pi*x(2)*x(4)*sqrt(1-.533^2)))*exp((-1/(2-2*.533^2))*((data(1)-x(1)).^2./(x(3)^2)+(data(2)-x(2)).^2./(x(4)^2)-(2*.533*(data(1)-x(1)).*(data(2)-x(2)))./(x(3)*x(4))))
fun([1,2,3,4],[data])
ans =
0.0233
What am I missing here? Is the function somehow summing up all the values, or just calculating the result for the first row?
0 commentaires
Réponse acceptée
Star Strider
le 1 Fév 2018
You are passing ‘data’ as a (100x2) matrix. You need to refer to the individual columns of ‘data’ in your function:
fun = @(x, data)(1/(2*pi*x(2)*x(4)*sqrt(1-.533^2)))*exp((-1/(2-2*.533^2))*((data(:,1)-x(1)).^2./(x(3)^2)+(data(:,2)-x(2)).^2./(x(4)^2)-(2*.533*(data(:,1)-x(1)).*(data(:,2)-x(2)))./(x(3)*x(4))));
That works correctly when I run it.
9 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!