Skip to main content

Volume of a solid sphere and graph for different radius using Matlab

Program

Calculate the volume of a solid sphere based on the user input given and also plot a graph for different values of radius with an interval of 0.5 and range of [r-5,r+5]. The relation for the volume of the sphere is given by:
Volume of a sphere formula and calculation using Matlab
Volume of a sphere
Where r is the radius of the sphere
You can learn more about sphere from here: 
2) Sphere- Wolfram

Solution

First of all let us understand the question before go into solving the problem using Matlab.
1) The question says that we will have to calculate the volume of a sphere by taking the input of the value of the radius from the user.
2) The question also asks us to draw the graph for a given set of range with a given set of interval. So the question asks us to take radius on x axis and volume on y axis. Next the difference between two points on the x axis should be 0.5 as said by the interval and finally we will have to draw the graph in the range [r-5,r+5]. Lets understand the range by taking an example, lets say user gives an input of 10, then we will have to draw the graph between the values [5,15] and the points will be [5,5.5,6,6.5,..........14,14.5,15].
I think you have understood what range and interval is. If you want a more detailed explanation about the same then refer:

I think if we have understood the question well then this problem is easy to be solved. Even if you haven't understood any of the above part then directly refer to the program section so that you can understand the program there by understanding the question. If you want detailed explanation about the program then refer to the explanation section. Some of the concepts you need to know to solve this program are as follows:
1) Requesting user input using Input function
2) variables in Matlab
3) operator precedence in Matlab
4) fprintf in matlab
5) comments in matlab
6) colon operator in Matlab
7) figure function in Matlab
8) clf in Matlab
9) plot function in Matlab
10) xlabel function in Matlab
11) ylabel function in Matlab
12) title function in Matlab
13) legend function in Matlab
14) grid in Matlab
15) Help in Matlab (This can be used to know more about any function in matlab if you don't know about any function or any other thing.)

Program


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
radius = input('Enter the radius of the sphere: ');
volume =(4/3)*(pi)*(radius^3);
fprintf('The volume of the sphere is: %.3f\n',volume)
fprintf('Please have a look at the graph\n')

%Now we are going to plot the graph
%We are going to use the colon operator to generate the
%Required vector for the x - axis
r = [radius-5:0.5:radius+5];
v = (4/3)*(pi)*(r.^3);%Watch out the period before ^. Find why in the explanation below
figure(1);
clf;
plot(r,v,'r.-');
xlabel('Radius of the sphere');
ylabel('Volume of the sphere');
title('Radius of sphere VS Volume of the sphere');
legend('Volume of sphere');
grid on;
I have saved this program as sphere_volume.m in my local computer.

Explanation

First of all I will explain you how to use the help function if you don't know any of the functions which we have used in the program. So why to use help function if we have internet or any other stuff. Okay even though you have an internet connection, you can get the same documentation available as on the internet just by typing the following:

>> help
This will give a very large list of all the available functions or others in Matlab so just by searching the function you require you will get the total documentation. Now if you know what function you need the documentation for then type help followed by the function and you will get the documentation. For example to get the documentation of the plot function then just type:

>> help plot
and you will get the whole documentation for the plot function in Matlab.
Now coming back to the program:
Line 1: I have requested the user to give the input of the radius of the sphere which he/she has measured in the physical world or just wanted to calculate based on some assumption.
Line 2: We are calculating the volume of the sphere with the radius that the user has given input just now. Here we are using the relation given in the question to find the volume of the sphere
Line3,4: We are displaying the output to the screen of the user, the volume which we just calculated. You can observe that there is %.3f in the fprintf to refer to volume. This means that we are requesting the Matlab to show the value of the volume upto 3 decimals(rounded to 3 decimals).
Line 6,7,8: All these are Matlab Comments
Line 9: We are using the colon operator to generate the vector within the given range as specified in the question and with the interval. To make it simple to understand refer to the following diagram:
Image displaying how the colon operator works in Matlab
Image displaying how the color operator works 
To explain accordingly as explained in the solution section, x is the lower limit in the range, y is the interval, and z is the upper limit in the range. So it becomes: range: [x,y] Interval: y. To know more about the colon operator you can refer to the following section: Colon : .
Line 10: In this line we have used the fixed point array power(.^) in matlab to compute power of each element of the vector. If you have used the simple ^ then you would get an error. 
Line 11: Here I have used the figure function to select the figure window if it is already there or create a new figure if it is not there.
Line 12: After selecting the figure then I have used the clf to clear current figure window if it has any.
Line 13: I have used the plot function to plot the graph between the radius vector and the volume vector. You can see that there are three elements in the parenthesis of the plot function. They are the vector on the x axis, vector to be used in y axis and the last text(string) withing the quotations represent as follows:(type 'help plot' to get more information)
Plot function parameters
Parameters used in the plot function

Line 14: xlabel function to label the x axis with a given name in the parenthesis.
Line 15: ylabel function to label the y axis with a given name in the parenthesis. 
Line 16: title function to add title to the given graph.
Line 17: legend function to show the legend and the text in the parenthesis will be shown as the legend.
Line 18:'grid on' This will switch on the grid lines in the graphs. Grids lines are the lines which are line the one which you see in a graph sheet. Remember grid on will switch on the grids and grid off will switch of the grids.

Input/Output

volume of the sphere and its graph matlab session
Input and output for a matlab session. Image also includes another window of the graph
Note that the window of the figure 1 is different from the command window. But for the sake of simplicity I have merged them both in the same image to make it simple for you.

Try it yourself

1) Draw the graph on a graph sheet and check whether we are getting the same graph as you got in the graph sheet. You can print a graph sheet from here: Print Free Graph Paper
2) Write a program to have the same functionality for a solid cylinder. Draw the graph for this too.
3) Try to write a similar program for a Hallow sphere. Now take two random values for radius(outer radius and inner radius)  such that outer radius > inner radius and draw the graph generating a few pairs of random values. 
Comment your programs in the comment box below so that others can have a look at your program if they want to!

Final Note

I have tried to explain every part in this program in such a way that it is easy to understand for everyone. If you still have any doubt or couldn't understand anything then please do contact me or simply comment in the comment box below. You can contact me from here: Contact me.
The program was high lighted using hilite.me.
Keywords: plot, figure, clf, xlabel, ylabel, title, legend, colon operator, fixed point array power. power of a number,fprintf, input,sphere, volume

Popular posts from this blog

Problem 60 Project Euler Solution with python

Prime pair sets The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property. Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime. This problem is j u st a brute force problem. If you have come here because you don't know the limit upto which you will h ave to gener ate the prime numbers t hen go ahe ad and t r y with 10,000 . When I first start ed solving the problem I chose 1 million(beca use most of the problem s on project E uler have this limit ), but it took very long for the computer to fin d the solution. After searching on the internet then I found many people choosing 10, 000 so I have changed my in put f rom 1 million to 10000 and the output was f ast. He...

Add/Embed SVG to Blogger website

In this post I will tell you my method(trick) of adding SVG images in a blogger website or blog. Before starting , the first thin g I am assu m ing is that you are aware of SVG if you are here. If not please see S calable V ec tor G raphics Recently when I tried to embed a SVG image for a post on pygal, I tried uploading the SVG file and blogger Image uploader came up with an error, because of which I had to find some other way.  SVG File upload Error in Blogger  I started sea rc hing Google " Embed SVG in Blogger " . I found blogorrhea , w h ich gave some i nformatio n on add ing SVG directly as a markup , which worked , but I faced another problem using this . Also th is guy has used lot of Javascript which was confusin g for me, being new to using SVG.   So I first t houg ht of learning on h ow to embed SVG in HTML and t his on e worked out. Actually we can embed SVG in HTML i n following ways: Using Object tag Using Iframe tag Using embed...

Making a quiz web app with python and flask

Edit : When you are creating a web app with h tml templates, then y ou will have to sa ve the html file in templates folder in the Current Wor ki ng Directory( CWD). If you save the file in the C W D directl y you will get a TemplateNotFound error. Thank you Udhay for pointing it out.   In this post we will create a quiz website using python . I will be using the flask framework . After reading this tutorial you will learn form submission , flask templates , python code in flask templates , shuffling the questions and options with the random module and few others.  Please note that this tutorial is not big as it seems to be. Some of the code has been rewritten to maintain consistency and also font size is somewhat big so that your eyes won't get stressed reading this tutorial. Also the content has not occupied the full width of the page. In this tutorial I am assuming that you are having a very basic understanding of the flask framework . Please refer the documenta...