Assignment help... Inputting double array into function.

1 view (last 30 days)
Hello everyone. This is my first post here. I have no coding experience and am a current student at U.C. Berkeley studying Engineering Physics. I am taking a programming course that is using matlab and I am TERRIBLE at programming. Anyway thanks for all the help and support in advance.
The assignment is to calculate the surface area and volume of a cylinder. I don't want a solution because I really need to learn this and some day wish to be pretty proficient with matlab as I will use it a lot for my major.
This is what I've done so far. It seems very basic.
function [ S , V ] = myCylinder( R,H )
S = (2*pi*R*H) + (2*pi*(R^2)); % Calculates the surface area of Cylinder.
V = (pi*(R^2)*H); % Calculates the volume of the Cylinder.
The problem I am having is it says I should be able to input the data as a double array.
So I could write
myCylinder([1,2],[2,4])
My attempt:
I was trying to use array indexing and reading up on that section in the text book but for the life of me after a long while I can not figure it out. Any tips and suggestions would be greatly appreciated. Thanks Guys!!
Anthony
PS having issues with inputting code into the forum. If anyone could explain an easier way for future use that would also be awesome.

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 2 Feb 2014
Edited: Azzi Abdelmalek on 2 Feb 2014
If you want to use vectors as input argument, replace * by .* and ^ by .^
function [ S , V ] = myCylinder( R,H )
S = (2*pi*R.*H) + (2*pi*(R.^2));
V = (pi*(R.^2).*H);
  4 Comments
Peter
Peter on 2 Feb 2014
Edited: Peter on 2 Feb 2014
Wow! That worked. So simple.
Thank you so much Azzi!
So even if there isn't some sort of Array set up in the function, adding the .* will automatically read each separate input as an array? What exactly is happening now that I added the .'s?
Edit...I guess what I am asking is how does matlab know which index of the array applies to which input variable. And why wouldn't
[S V] = myCylinder([2,4])
also work since it's just another array.
Azzi Abdelmalek
Azzi Abdelmalek on 2 Feb 2014
In your function there are two inputs R and H , [2 4] is one input

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!