I am new to Matlab, and so far I learned how to evaluate functions of multiple var.s over a single vector of data, as in the following example,
>>data = [1,2,3,4,2,2.5,2.9,1.8,-1,1.8]
>>fun=@(x) (1/(sqrt(2*pi)*x(2)))*exp((-(data-x(1)).^2)/(2*x(2)^2)) %A Normal distribution
>>fun([1,2])
Columns 1 through 9
0.1995 0.1760 0.1210 0.0648 0.1760 0.1506 0.1270 0.1841 0.1210
Column 10
0.1841
This works as expected, but what about a function like the following, with multiple data sources,
>>data1 = [1,2,3,4,2,2.5,2.9,1.8,-1,1.8]
>>data2 = [1,2,3.1,4.1,2.1,2.51,3.1,-1,1.9,2]
>>p = .5092
>>fun = @(x) (1/(2*pi*x(2)*x(4)*sqrt(1-p^2))) * exp( (-1/(2-2*p^2)) * ( (data1-x(1)).^2/(x(3)^2) + (data2-x(2)).^2/(x(4)^2) - (2*p(data1-x(1))*(data2-x(2)))/(x(3)*x(4)) ) ) % A joint-probability distribution
>>fun([1,2,3,4])
Subscript indices must either be real positive integers or logicals.
Error in
@(x)(1/(2*pi*x(2) . . .
This last equation is just a joint probability distribution, and every observation is made up of a paired x and y value. How would I run this and similar functions over both data1 and data2 at the same time, being iterated over the same index for both of them, one number at a time, producing a matrix of outputs?
The reason I can't simply run a loop is because I need to enter this function into a fminunc()
function optimization process and have it be able to evaluate the F. for each pair of values.
You wrote 2*p(data1-x(1))
then p
is viewed as vector, change this to 2*p.*(data1-x(1))
. A second error is (data1-x(1))*(data2-x(2))
. This is a matrix multiplication, and since the dimensions don't match will give an error. I assume you want a scalar multiplication, then again add the .
so it becomes (data1-x(1)).*(data2-x(2))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.