필터 지우기
필터 지우기

How to run function over variables located within matrix?

조회 수: 3 (최근 30일)
Michael Ziedalski
Michael Ziedalski 2018년 1월 28일
답변: Walter Roberson 2018년 1월 28일
Hello, all. So I am a Matlab newbie, and my first major project is trying to create a function that maximizes any mathematical function that I input into it for some variables over some data observations. For ex., like finding the parameters of the normal distribution that maximizes said normal dist. function for some values of x.
Thing is, sometimes my function has more than one data source, and I'd like to be able to create one matrix, with each of its columns corresponding to a different observation the function is supposed to run over.
data1 = [1, 2, 3];
data2 = [6,7,8];
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))));
fun([1,2,3,4])
Here, I get a vector of values as expected, but how could I do the same with just one "data" vector, like
data=[data1;data2];
fun([1,2,3,4]) ?
Is it possible?

채택된 답변

Walter Roberson
Walter Roberson 2018년 1월 28일
You would need to have some kind of string template and then for the individual variables you wanted to merge together, you would have to replace the strings of the variable names with references into the merged variable based upon the lengths of example vectors at specialization time. This could be tricky because you might have indexing into the variables -- for example if you had data2(3) then that could not be replaced by data(4:6)(3)
Your tags refer to the symbolic toolbox. If you are doing this through the symbolic toolbox instead of writing the anonymous functions by hand, then use matlabFunction with the 'vars' parameter, and put the variables to be merged into a vector inside a cell array. So for example,
data1_vec = sym('data1_', [1 3]);
data2_vec = sym('data2_', [1 3]);
expanded_expression = subs(EXPRESSION, {data1, data2}, {data1_vec, data2_vec});
fun_numeric = matlabFunction( expanded_expression, 'vars', {x, [data1_vec, data2_vec]});
This would tell MATLAB to create a function with two arguments, one of which is x and the other is a vector that is to be indexed as appropriate to act as the elements data1_1 data1_2 data1_3 data2_1 data2_2 data2_3
After that, since it appears that your data vector is to be static during fun:
fun = @(x) fun_numeric(x, data);
where data is the fixed numeric vector.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Conversion Between Symbolic and Numeric에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by