フィルターのクリア

Need help running simple equation over vector of data?

6 ビュー (過去 30 日間)
Michael Ziedalski
Michael Ziedalski 2018 年 2 月 1 日
コメント済み: Star Strider 2018 年 2 月 3 日
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
Michael Ziedalski 2018 年 2 月 3 日
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.
Star Strider
Star Strider 2018 年 2 月 3 日
As always, our pleasure!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by