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 Center および File ExchangeMATLAB についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by