how evaluate anonymus function with array?

2 次查看(过去 30 天)
Once an anonymus function is built, how do you evaluate it with an array?
My solution does work, but it doesnt solve the answer, because I use a trick to convert the array into a string, and then eval this:
% May the handle function (or anonymus) for example
Fopt=@(x,y) sin(x).*sin(y);
x0=[1,1];
N=length(x0);
str=sprintf('%f,',x0(1:end-1));
str=sprintf('%s%f',char(str),x0(end))
eval(['Fopt(',str,')'])
My desire is to do this just like:
Fopt(x0)
Thanks

采纳的回答

Matt J
Matt J 2014-1-8
编辑:Matt J 2014-1-8
You would not write the anonymous function to take separate scalar arguments. You would write it to accept a single vector argument and use vector operations to get the result,
Fopt=@(x) sin(x(1)).*sin(x(2));
  1 个评论
Matt J
Matt J 2014-1-8
编辑:Matt J 2014-1-8
Or, you could handle vectors x of arbitrary length with
Fopt=@(x) prod(sin(x));

请先登录,再进行评论。

更多回答(1 个)

Juan
Juan 2014-1-8
Thanks! I guessed it could not be hard.
I shall share some code it may help someone:
METOD 1, using multiples variables, each one is an array, in anonymus function:
clc,clear all,close all
Fopt=@(x,y) sin(x).*sin(y);
x0=[1,1];
x=1e1*[(-x0(1)),x0(1)];
x=linspace(x(1),x(2),1e2);
y=1e1*[(-x0(2)),x0(2)];
y=linspace(y(1),y(2),1e2);
[X,Y] = meshgrid(x,y);
f=Fopt(X,Y);
plot3(X,Y,f,'.','MarkerSize',4.55),grid on
% surf y mesh
figure(2)
surf(x,y,f),grid on
figure(3)
mesh(x,y,f);hold on,plot3(X,Y,f,'.','MarkerSize',4.55),grid on,hold off
METOD 2, using one variable , a matrix of variables , like the Matts answer,in anonymus function:
clc,clear all,close all
Fopt=@(x) sin(x(:,:,1)).*sin(x(:,:,2));
x0=[1,1];
a=1e1*[(-x0(1)),x0(1)];
x(:,1)=linspace(a(1),a(2),1e2);
b=1e1*[(-x0(2)),x0(2)];
x(:,2)=linspace(b(1),b(2),1e2);
v(:,:,1)=repmat(x(:,1),[1,length(x(:,1))])';
v(:,:,2)=repmat(x(:,2),[1,length(x(:,2))]);
a=x(:,1);
b=x(:,2);
x=v;
plot(x(:,:,1),x(:,:,2),'.')
f=Fopt(x);
plot3(x(:,:,1),x(:,:,2),f,'.','MarkerSize',4.55),grid on
% surf y mesh
figure(2)
surf(a,b,f),grid on
figure(3)
mesh(a,b,f),hold on,plot3(x(:,:,1),x(:,:,2),f,'.','MarkerSize',4.55),grid on,hold off
Suggestions and corrections of code will be thankful received.

类别

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

产品

Community Treasure Hunt

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

Start Hunting!

Translated by