What code would you input to represent the equation for the volume of a sphere without getting an undefined variable error?

 Accepted Answer

Easy, peasy.
V=(4*pi*r.^3)/3;
I added a semi-colon at the end, and I used .^ for the exponent, in case r is an array or vector.
Since you apparently are getting an undefined variable error, then you need to tell us more.
My guess is, you actually want to create a function of the radius, so that r is indeed undefined at the time you create the function.
V= @(r ) (4*pi*r.^3)/3;
Or possibly, you want to create this in symbolic form. In that case, you need to define r as symbolic.
help syms
How can we know what is in your mind?

4 Comments

so how would I define the variable r without giving it a value?
Again, it depends!
1. Do you have the symbolic toolbox?
2. Do you REALLY want to create this as symbolic? Too often people think they do want that, when the very next question they will ask is "Why does my code run like a dog with two legs?" Symbolic computations are relatively expensive to do in terms of CPU.
If all that you wanted to do is to create a function to compute the volume of a sphere as a function of some radius r, then I already showed you how to do that!
I would seriously suggest that you spend a little time reading the help for the syms function. But as seriously, you need to consider if that is what you want to do. Far too often, people use the wrong tool for their problems.
syms r
yeah I don't have the symbolic toolbox and whenever I type help syms, it corrects it to help sum. I suppose this is a result of not having the symbolic toolbox. So I guess volume as a function of the radius is the next best approach.
Yes, you must not have that TB. Within limits, you COULD use my sympoly toolbox. It is on the File Exchange. It is admittedly limited though.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!