How can I vectorize a function?

144 ビュー (過去 30 日間)
David Franco
David Franco 2018 年 3 月 1 日
コメント済み: Star Strider 2018 年 3 月 24 日
The function I want to vectorize is Cross-in-Tray Function (2-D):
f(X,Y) = -0.0001*(abs(sin(X)*sin(Y)*exp(abs(100-sqrt(X^2+Y^2)/pi)))+1)^0.1;
I want to use the command (to plot the function):
fsurf(@(x,y) crossintrayfcn([x,y]))
I have this two function codes:
function z = crossintrayfcn(xx)
x = xx(:,1);
y = xx(:,2);
expcomponent = abs(100-(sqrt(x.^2 + y.^2)/pi));
z = -0.0001*((abs(sin(x).*sin(y).*exp(expcomponent))+1).^0.1);
end
And:
function [y] = crossintrayfcn(xx)
x1 = xx(1);
x2 = xx(2);
fact1 = sin(x1)*sin(x2);
fact2 = exp(abs(100 - sqrt(x1^2 + x2^2)/pi));
y = -0.0001 * (abs(fact1*fact2) + 1)^0.1;
end
But they plot nothing!
Thanks!

採用された回答

Star Strider
Star Strider 2018 年 3 月 1 日
Vectorising it simply requires using element-wise operations:
f = @(X,Y) -0.0001*(abs(sin(X).*sin(Y).*exp(abs(100-sqrt(X.^2+Y.^2)/pi)))+1).^0.1;
[x,y] = meshgrid(linspace(-10, 10, 49));
figure
surfc(x, y, f(x,y))
grid on
See the documentation on Array vs. Matrix Operations (link) and Vectorization (link) for details.
  9 件のコメント
Yair Altman
Yair Altman 2018 年 3 月 24 日
@StarStrider - thanks, duly noted
Star Strider
Star Strider 2018 年 3 月 24 日
@Yair — My pleasure.

サインインしてコメントする。

その他の回答 (1 件)

David Franco
David Franco 2018 年 3 月 5 日
Because of the above problems I'm using my own function with surfc to replace fsurf:
function z = plotfcn(fcn,range,grid,shad)
% PLOTFCN evaluate and plot a 3D function
% INPUT:
% FCN - @myFunction (function handle)
% RANGE - [x1min x1 max x2min x2max] (default = [-10 10 -10 10])
% GRID - grid size for the function evaluation (default = 101)
% SHAD - set color shading properties (default = 0)
% 0 = faceted (continued colormap with black mesh lines)
% 1 = interp (interpolated colormap)
% 2 = flat (continued colormap)
% OUTPUT:
% Z - function eval (GRID x GRID)
% EXAMPLE:
% z = plotfcn2(@ackleyfcn, [-32 32; -32 32], 200, 1);
switch nargin
case 4
case 3
shad = 0;
case 2
shad = 0;
grid = 101;
case 1
shad = 0;
grid = 101;
range = [-10 10 -10 10];
otherwise
disp('Not enough input arguments. Function required.')
return
end
x1 = meshgrid(linspace(range(1,1), range(1,2), grid));
x2 = meshgrid(linspace(range(1,3), range(1,4), grid))';
xx = [x1(:),x2(:)];
f = fcn(xx);
f = reshape(f,size(x1));
if nargout == 1
z = f;
end
figure
surfc(x1,x2,f)
title([func2str(fcn), ' [x,y]'])
colormap jet
if shad == 1
shading interp
elseif shad == 2
shading flat
end
end

カテゴリ

Help Center および File ExchangeSurface and Mesh Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by