Asked by David Franco
on 2 Mar 2018

The function is:

x = -10:10;

y = -5:5;

for j = 1:21

for i = 1:11

f(i) = - 20 * exp( - 0.2 * sqrt( ( 1/2 ) * sum( x(j)^2 + y(i)^2 ) ) );

end

z(j,:) = f;

end

Thanks!

Answer by Andrei Bobrov
on 2 Mar 2018

Edited by Andrei Bobrov
on 2 Mar 2018

Accepted Answer

% MATLAB >= R2016b

z = - 20 * exp( - 0.2 * sqrt( .5 * sum( x(:).^2 + y(:)'.^2 ) ) );

% MATLAB <= R2016a

[xx,yy] = ndgrid(x,y);

z = - 20 * exp( - 0.2 * sqrt( .5 * sum( xx.^2 + yy.^2 ) ) );

David Franco
on 2 Mar 2018

Thanks for the answer Andrei, but the results are different:

In the original code z = 21x11

In your codes z = 1x11

Any suggestions on how to fix this?

David Franco
on 2 Mar 2018

I figured out:

Removing the sum command the results are the same.

Thanks!

Sign in to comment.

Answer by per isakson
on 2 Mar 2018

Edited by per isakson
on 2 Mar 2018

Yes, try this

>> max( cssm, [], 1 )

ans =

0 0 0 0 0 0 0 0 0 0 0

>>

where

function dz = cssm()

x = -10:10;

y = -5:5;

f = nan(1,11);

z = nan(21,11);

%

for j = 1:21

for i = 1:11

f(i) = - 20 * exp( - 0.2 * sqrt( ( 1/2 ) * sum( x(j)^2 + y(i)^2 ) ) );

end

z(j,:) = f;

end

vectorized version

x02 = repmat( reshape( x, [], 1 ), 1,length(y) );

y02 = repmat( y, length(x),1 );

z02 = - 20 * exp( - 0.2 * sqrt( ( 1/2 ) * ( x02.^2 + y02.^2 ) ) );

%

dz = abs( z02 - z );

end

on R2016a

btw: Isn't true that sum in this case has no effect?

David Franco
on 2 Mar 2018

It worked, but how can I extrapolate to higher dimensions?

Ackley's Function:

z = -20*exp(-0.2*sqrt((1/d)*sum(x^2)))-exp((1/d)*sum(cos(2*pi*x)))+20+exp(1);

where d is the dimension of the input.

Thanks!

per isakson
on 2 Mar 2018

David Franco
on 2 Mar 2018

Thanks per isakson!

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.