필터 지우기
필터 지우기

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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by