home

Scientific Computing (Psychology 9040a)

Fall, 2021

Volume of a sphere: sample solution


Here is a basic solution using 3.14 as the approximate value of \(\pi\):

r = 5;
v = (4/3) * 3.14 * r*r*r;
disp(v)

It turns out MATLAB knows the value of \(\pi\), and has a built-in variable called pi. Also we can use MATLAB’s notation for “to the power of” to code r*r*r as r^3:

r = 5;
v = (4/3) * pi * r^3;
disp(v)

Finally if we wanted to display a nice message along with the value of v we could do it this way:

fprintf('the volume of a sphere with radius %.3f is %.3f\n', r, v);