Need help running simple equation over vector of data?

6 次查看(过去 30 天)
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?

采纳的回答

Star Strider
Star Strider 2018-2-1
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 个评论
Michael Ziedalski
Walter and Star Strider, through your answers I have figured out little, but substantial, Matlab details that have haunted me for the past couple of weeks. Especially after Strider's answer, now my code works perfectly; thank you very much, all.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by