Azzera filtri
Azzera filtri

how evaluate anonymus function with array?

2 visualizzazioni (ultimi 30 giorni)
Juan
Juan il 8 Gen 2014
Risposto: Juan il 8 Gen 2014
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

Risposta accettata

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

Accedi per commentare.

Più risposte (1)

Juan
Juan il 8 Gen 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.

Categorie

Scopri di più su Graphics Performance in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by