Solved

# How to do a contour Plot of a Sphere Function

Posted on 2013-05-25
1,061 Views
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.
??? 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?
0
Question by:wish_C
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 15
• 7

LVL 84

Expert Comment

ID: 39196845
What do you expect Z = sphere(X1,X2) to do?
Which line of your code is at 89?  Which is at 73?
What is Z?
0

Author Comment

ID: 39196865
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:

``````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
``````
0

Author Comment

ID: 39197181
Any idea on how to solve this please?
0

LVL 37

Expert Comment

ID: 39199074
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
0

Author Comment

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

``````  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
``````
?
0

LVL 37

Expert Comment

ID: 39199265
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.
0

Author Comment

ID: 39199329
Here is the sphere function:
``````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?
0

Author Comment

ID: 39202523
This is what i am trying to achieve in the above code.

0

LVL 37

Expert Comment

ID: 39202559
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)
0

Author Comment

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

LVL 37

Expert Comment

ID: 39203010
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?
0

Author Comment

ID: 39206530
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.
0

Author Comment

ID: 39208459
Any body knows  Estimation of Distribution Algorithm (EDA) in evolutionary computation?
0

LVL 37

Expert Comment

ID: 39208711
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.
0

Author Comment

ID: 39208900
@TommySzalapski, are you studying at Missouri University of Science and Technology? PhD?
0

Accepted Solution

wish_C earned 0 total points
ID: 39209109
Now i have the sphere plotted now. Just trying to create some movie for each Generation of the Algorithm.
0

LVL 37

Expert Comment

ID: 39209128
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.
0

Author Comment

ID: 39209241
0

Author Comment

ID: 39211869
``````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?
0

Author Comment

ID: 39212310
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
0

Author Comment

ID: 39213804
Anyone has clue on this to help me out please.
0

LVL 37

Expert Comment

ID: 39223213
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.
0

Author Closing Comment

ID: 39283788
I solve the issue by myself.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article seeks to propel the full implementation of geothermal power plants in Mexico as a renewable energy source.
This article will show, step by step, how to integrate R code into a R Sweave document
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templaâ€¦
###### Suggested Courses
Course of the Month1 day, 23 hours left to enroll