wish_C

asked on

# How to do a contour Plot of a Sphere Function

Hi Experts,

I am trying to plot a sphere function in 2D or 3D using contour plot, but i keep on having the following error.

Here is the sphere function:

If i use one input argument say

Z = sphere(X1);

I have the error below:

Here is the code to plot the sphere using contour plot.

How can i fix this error so that i can plot the contour of the sphere? Any idea please?

I am trying to plot a sphere function in 2D or 3D using contour plot, but i keep on having the following error.

??? Error using ==> sphere Too many input arguments.

Error in ==>sphereplotting at 89

Z = sphere(X1,X2);

Here is the sphere function:

```
function ph = sphere(x)
ph = sum(x.*x, 2);
end
```

If i use one input argument say

Z = sphere(X1);

I have the error below:

??? Error using ==> contour at 73

Z must be size 2x2 or greater.

Here is the code to plot the sphere using contour plot.

```
cmin = -25;
cmax = 25;
ngrid = 25;
cvals = linspace(cmin, cmax, ngrid); % Create the mesh
[X1, X2] = meshgrid(cvals, cvals); % Create the grid
% k=1,l=2;
Z = sphere(X1,X2);
figure;
contour(X1, X2, Z);
```

How can i fix this error so that i can plot the contour of the sphere? Any idea please?

ASKER

I expect Z to return at least a 2x2 matrix. Z is supposed to be the height of the sphere and X1 the x-axis and X2 the y-axis.

Here is the whole code:

Here is the whole code:

```
M = 100; % population size
n = 2;
pop = 0 + 1.*randn(M,n);
[popSize d] = size(pop);
G = 25; % number of generations for the fitness evaluation function
Max_F = 1000; % maximal number of FEs
options.optmType = 'max';
y = zeros(1,G);
for i =1:G
eval = sphere(pop); % fitness evaluation of the initial population.
% Setting Criteria for selecting N(<=M)
if ~isfield(options, 'optmType')
error('Please provide optimisation type {min, max}');
end
% define best population size
if isfield(options, 'topSize')
topSize = options.topSize;
if topSize > popSize
disp('Warning: topSize is larger than popSize, will use, popSize/10');
topSize = 0.25 * popSize;
options.topSize = topSize;
end
else
topSize = 0.25 * popSize;
options.topSize = topSize;
end
% all initial pop are top_x
top_x = pop;
% Criteria for selecting top 'topSize' individuals based on fitness
% values(eval)
if strcmp(options.optmType, 'min')
[void, b] = sort(eval, 'descend'); % maximising
else
[void, b] = sort(eval, 'ascend'); % minimising
end
top_x = pop(b(1:options.topSize),:); % select top individuals
optm_x = pop(b(1),:); % save optimal parameter
fv = eval(b(1)); % save optimal func. value
mu = mean(top_x); % mean vector calculation
Sigma = cov(top_x); % Covariance calculation
pop = mvnrnd(mu,Sigma,M); % Calculate joint probability distribution of selected individuals(sampling)
dstring = [num2str(M), ' samples are generated.'];
subplot(1,2,1);
y(i) = sphere(optm_x);
plot(y(1:i));
xlabel('Generations')
ylabel(' Best Individuals')
title(sprintf('At the some Generations'))
%axis('equal');
cmin = -25;
cmax = 25;
ngrid = 25;
cvals = linspace(cmin, cmax, ngrid); % Create the mesh
[X1, X2] = meshgrid(cvals, cvals); % Create the grid
Z = sphere(X1);
subplot(1,2,2);
contour(X1, X2, Z);
end
```

ASKER

Any idea on how to solve this please?

Your sphere function is wrong. It needs to take two arguments (x and y coordinates). You have X1 and X2 (which look good). You did try to pass them to sphere before, but it was only set to take one argument. It certainly needs both (actually maybe a third for the radius).

The function for a sphere is x^2+y^2+z^2 = r^2 (where r is the radius).

So you need to solve that equation for Z and that's your sphere function.

function ph = sphere(x, y, r)

ph = 'sphere equation

end

The function for a sphere is x^2+y^2+z^2 = r^2 (where r is the radius).

So you need to solve that equation for Z and that's your sphere function.

function ph = sphere(x, y, r)

ph = 'sphere equation

end

ASKER

The sphere function is ok with the way it is. If i change it, it will affect this part of the code:

this is what i have done to get rid of the error:

I just modify the sphere evaluation function to This:

this :

Any idea why the contour plot is showing vertical lines not contours?

Is is reasonable to use

` eval = sphere(pop); % fitness evaluation of the initial population.`

this is what i have done to get rid of the error:

I just modify the sphere evaluation function to This:

`Z = arrayfun(@sphere, X1);`

The surf & Plot3 plots show a parabola, but the contour plot shows only vertical lines, not contours. I don't know why?this :

` contour(X1, X2, Z); `

shows the vertical lines not contours, why?`surf(X1, X2, Z); and Plot3(X1, X2, Z); `

show parabola which is reasonable.Any idea why the contour plot is showing vertical lines not contours?

Is is reasonable to use

`arrayfun`

?
The plot is showing the data you gave it. Your sphere function is not giving the correct points.

Post your sphere function again. You modified it to use X1 and X2 right? You need to change it to take both.

Post your sphere function again. You modified it to use X1 and X2 right? You need to change it to take both.

ASKER

Here is the sphere function:

In this code i have given the sphere function an input of X1

not an input of X1 and X2. i did this because i don't want it to affect this part of the code:

but like i said the contour plot:

```
function ph = sphere(x)
ph = sum(x.*x,2);
end
```

In this code i have given the sphere function an input of X1

`Z = arrayfun(@sphere, X1);`

not an input of X1 and X2. i did this because i don't want it to affect this part of the code:

`eval = sphere(pop); `

but like i said the contour plot:

`contour(X1, X2, Z); `

Is showing vertical line, not contour line. This is not how it should be. How can i fix this?
ASKER

So the way the contour function works is you pass it a grid and the Z axis values for the X and Y coordinates.

So you pass X1 and X2 as the x and y coords for the grid. This looks fine.

Then you pass Z for the actual Z axis values (the "height" of the contour) at each point in the grid.

Your function that gives these values just squares the X axis values. That's not a sphere.

Your sphere function needs to actually generate a sphere if you want to see a sphere shaped curve. You'll need to re-evaluate what you really want from sphere(pop). Maybe you need two functions? You need to use the actual equation of a sphere to get a sphere z = sqrt(r^2 - x^2 - y^2)

So you pass X1 and X2 as the x and y coords for the grid. This looks fine.

Then you pass Z for the actual Z axis values (the "height" of the contour) at each point in the grid.

Your function that gives these values just squares the X axis values. That's not a sphere.

Your sphere function needs to actually generate a sphere if you want to see a sphere shaped curve. You'll need to re-evaluate what you really want from sphere(pop). Maybe you need two functions? You need to use the actual equation of a sphere to get a sphere z = sqrt(r^2 - x^2 - y^2)

ASKER

The sphere function i post above is what i am using, i am trying to test it. Is it not possible to plot it?

Okay. So you aren't actually trying to plot a sphere. That's fine.

You are still going to run into the problem that your Z is a vector, not a matrix.

If you just output Z, what do you get for the values?

You are still going to run into the problem that your Z is a vector, not a matrix.

If you just output Z, what do you get for the values?

ASKER

Is there anyone here who knows Estimation of Distribution Algorithm (EDA). This is the algorithm i am trying to implement to understand it. I am trying to plot the sphere function to test it. The test functions can be found Here.

I want to plot the sphere function as a surface or a contour plot, and the position and fitness value of the best individual superimposed with it. The plot will change in each generation so i get a movie. Also, on another figure, i want to plot the contour of the sphere function superimposed with the entire population, with the retained fit individuals colored in red. This from generation to generation should give another movie.

Anyone one has an idea on how this is coded.

I want to plot the sphere function as a surface or a contour plot, and the position and fitness value of the best individual superimposed with it. The plot will change in each generation so i get a movie. Also, on another figure, i want to plot the contour of the sphere function superimposed with the entire population, with the retained fit individuals colored in red. This from generation to generation should give another movie.

Anyone one has an idea on how this is coded.

ASKER

Any body knows Estimation of Distribution Algorithm (EDA) in evolutionary computation?

What is it that you want your sphere function to be doing?

Currently, it is taking a vector, squaring each element of the vector and returning it summed by row.

So sphere([1, 2, 3, 4]) returns [1, 4, 9, 16];

if you passed it

[[1] [2] [3] [4]]

it would return [[31]] (sum of all elements).

Is that what you want? In order to make a contour, your Z needs to be a matrix, not a vector.

If sphere was x*transpose(x) instead of sum(x.*x,2) then you could pass it a vector and it would return a matrix.

Currently, it is taking a vector, squaring each element of the vector and returning it summed by row.

So sphere([1, 2, 3, 4]) returns [1, 4, 9, 16];

if you passed it

[[1] [2] [3] [4]]

it would return [[31]] (sum of all elements).

Is that what you want? In order to make a contour, your Z needs to be a matrix, not a vector.

If sphere was x*transpose(x) instead of sum(x.*x,2) then you could pass it a vector and it would return a matrix.

ASKER

@TommySzalapski, are you studying at Missouri University of Science and Technology? PhD?

ASKER CERTIFIED SOLUTION

membership

Create an account to see this answer

Signing up is free. No credit card required.

Glad to hear it's plotting now.

Yes. I am currently finishing my PhD at S&T. Do I know you? You can email me if you want to take the social aspect of this conversation offline. I'm sure you can find my email address if you are at the university.

Yes. I am currently finishing my PhD at S&T. Do I know you? You can email me if you want to take the social aspect of this conversation offline. I'm sure you can find my email address if you are at the university.

ASKER

I added you on facebook. abd i also added you on google talk or Google hangout. If you accept me, i will ping you.

ASKER

```
K= 4
for l = 1 : K
contour(X,Y,ph);
hold on
plot(bestId, 'rx');
end
```

The above code should superimpose contour plot and BestId. For each loop of l, a bestId is generated and superimposed with the contour plot. This generation of BestInd should take place for each l. but among the generations of bestId from 1 to 4, there is one which is the best of them and we should get that after four generation which is superimposed with the contour plot. Now i want this generation to be a movie for reach iteration from 1 to 4, so that i can see how the bestId are generated untill the best(optimal) one is achieved. this is what i meant by movie in matlab. Any idea on how this could be done?

ASKER

Can someone help me with the above problem please? Here is what i am trying to achieve.

Sample.ppt. If you download the ppt and have a slideshow, you will see how i want the plot to be at each generation, thus creating a Movie to see how the points moves slowly to the global optimum.

The whole code i wrote to achieve this is in my post @ ID: 39196865

Sample.ppt. If you download the ppt and have a slideshow, you will see how i want the plot to be at each generation, thus creating a Movie to see how the points moves slowly to the global optimum.

The whole code i wrote to achieve this is in my post @ ID: 39196865

ASKER

Anyone has clue on this to help me out please.

If the original problem is solved (plotting the contour), then your best bet would be to close this question (since it was answered) and open a new one for the new problem (the movie). That way other people will look at it besides just me and it will have a better chance at a good fast answer.

I will be happy to look at this again, but I don't have MATLAB on this computer and it may be a bit before I have the time. If you use the same zones, I will get an email when you ask the next step.

I will be happy to look at this again, but I don't have MATLAB on this computer and it may be a bit before I have the time. If you use the same zones, I will get an email when you ask the next step.

ASKER

I solve the issue by myself.

Which line of your code is at 89? Which is at 73?

What is Z?