Assignment help... Inputting double array into function.

13 次查看(过去 30 天)
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.

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2014-2-2
编辑:Azzi Abdelmalek 2014-2-2
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 个评论
Peter
Peter 2014-2-2
编辑:Peter 2014-2-2
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 2014-2-2
In your function there are two inputs R and H , [2 4] is one input

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by