how evaluate anonymus function with array?

조회 수: 6 (최근 30일)
Juan
Juan 2014년 1월 8일
답변: Juan 2014년 1월 8일
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에서 MATLAB에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by