how evaluate anonymus function with array?

1 view (last 30 days)
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

Accepted Answer

Matt J
Matt J on 8 Jan 2014
Edited: Matt J on 8 Jan 2014
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 Comment
Matt J
Matt J on 8 Jan 2014
Edited: Matt J on 8 Jan 2014
Or, you could handle vectors x of arbitrary length with
Fopt=@(x) prod(sin(x));

Sign in to comment.

More Answers (1)

Juan
Juan on 8 Jan 2014
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.

Categories

Find more on Graphics Performance in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!