Solved

How to do a contour Plot of a Sphere Function

Posted on 2013-05-25
23
1,015 Views
Last Modified: 2013-11-25
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

Open in new window


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);

Open in new window


How can i fix this error so that i can plot the contour of the sphere? Any idea please?
0
Comment
Question by:wish_C
  • 15
  • 7
23 Comments
 
LVL 84

Expert Comment

by:ozo
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

by:wish_C
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

Open in new window

0
 

Author Comment

by:wish_C
ID: 39197181
Any idea on how to solve this please?
0
 
LVL 37

Expert Comment

by:TommySzalapski
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

by:wish_C
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.

Open in new window


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);

Open in new window

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); 

Open in new window

shows the vertical lines not contours, why?

surf(X1, X2, Z); and Plot3(X1, X2, Z); 

Open in new window

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

Open in new window

?
0
 
LVL 37

Expert Comment

by:TommySzalapski
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

by:wish_C
ID: 39199329
Here is the sphere function:
function ph = sphere(x)
         ph = sum(x.*x,2);
   
end

Open in new window


In this code i have given the sphere function an input of X1
Z = arrayfun(@sphere, X1);

Open in new window


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); 

Open in new window


but like i said the contour plot:
contour(X1, X2, Z); 

Open in new window

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

Author Comment

by:wish_C
ID: 39202523
This is what i am trying to achieve in the above code.
Click here to see it.

Any idea please?
0
 
LVL 37

Expert Comment

by:TommySzalapski
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

by:wish_C
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

by:TommySzalapski
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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

by:wish_C
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

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

Expert Comment

by:TommySzalapski
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

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

Accepted Solution

by:
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

by:TommySzalapski
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

by:wish_C
ID: 39209241
I added you on facebook. abd i also added you on google talk or Google hangout. If you accept me, i will ping you.
0
 

Author Comment

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

Open in new window


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

by:wish_C
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

by:wish_C
ID: 39213804
Anyone has clue on this to help me out please.
0
 
LVL 37

Expert Comment

by:TommySzalapski
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

by:wish_C
ID: 39283788
I solve the issue by myself.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Iteration: Iteration is repetition of a process. A student who goes to school repeats the process of going to school everyday until graduation. We go to grocery store at least once or twice a month to buy products. We repeat this process every mont…
Prime numbers are natural numbers greater than 1 that have only two divisors (the number itself and 1). By “divisible” we mean dividend % divisor = 0 (% indicates MODULAR. It gives the reminder of a division operation). We’ll follow multiple approac…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now