Writing code to call functions

조회 수: 3 (최근 30일)
Spaceman
Spaceman 2024년 2월 26일
댓글: Spaceman 2024년 2월 26일
Given:
Find: Create a function that calculates the surface area of a sphere when provided with a radius as the input argument. Your code should work for both scalar radius values or an array of radii.
My Solution:
function A = AreaSphere(radius)
A=4*pi.*r^2
end
Code to call your function
r=randi(10,3,1);
Area=AreaSphere(r)
My Issue: I don't think I've learned how to properly call functions because I keep getting errors when trying to run function.

채택된 답변

Stephen23
Stephen23 2024년 2월 26일
"I don't think I've learned how to properly call functions because I keep getting errors when trying to run function."
The problem is how you have written the function: you defined one input argument RADIUS which you did not use anywhere. And then inside the function you refer to a variable/function named R which you did not define anywhere.
You also need to use array operations for element-wise operations:
r=randi(10,3,1);
Area = AreaSphere(r)
Area = 3×1
50.2655 201.0619 314.1593
function A = AreaSphere(radius)
A = 4*pi.*radius.^2;
end % ^^^^^^^^
  댓글 수: 1
Spaceman
Spaceman 2024년 2월 26일
Genius. I understand the error of my ways now. I was getting confused on how to define and call what I had defined.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

태그

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by