Task: Write a function named areaCircle to calculate the area of a circle. The function should take one input that is the radius of the circle. The function should work if the input is a scalar, vector, or matrix. The function should return, one ouput, the same size as the input, that contains the area of a circle for each correspoding element. If the input contains negative numbers, the function should return the value -1 at those locations to indicate the error.
These are code to call funtion. r1 = 2; area1 = areaCircle(r1) r2 = [2 5; 0.5 1]; area2 = areaCircle(r2) r3 = [1 1.5 3 -4]; area3 = areaCircle(r3)

댓글 수: 2

James Tursa
James Tursa 2018년 8월 3일
What have you done so far? What specific problems are you having with your code?
function area = areaCircle(r)
areaCircle(r)=pi.*(r.*r);
r1=2;
area1=areaCircle(r1)
r2= [2 5; 0.5 1];
area2=areaCircle(r2)
r3 = [1 1.5 3 -4];
area3=areaCircle(r3)
end

댓글을 달려면 로그인하십시오.

 채택된 답변

James Tursa
James Tursa 2018년 8월 3일
편집: James Tursa 2018년 8월 3일

0 개 추천

This line
function area = areaCircle(r)
means the function input is r and the output is area. So you need to assign the result of your calculation to the variable area like this:
area = pi.*(r.*r);
On top of this basic calculation, you need to account for negative inputs. So your function code will look something like this:
% You put text here to explain the function purpose
function area = areaCircle(r)
area = pi.*(r.*r);
% you put more code here to account for negative values that might be in r
end
So the only thing left for you to do is add that extra code for negative r values. I.e., change all elements of area to -1 where the corresponding r value is negative.
All of the other code you show above starting with the r1=2 line is NOT part of the function code, but is how you call the function from the command line or from other code.
Put the function code in a file called areaCircle.m, and then run your other code e.g. from the command line.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2018년 8월 3일

편집:

2018년 8월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by