put it in a function

조회 수: 2 (최근 30일)
Mingxuan
Mingxuan 2022년 11월 11일
답변: RAGHUNATHRAJU DASHARATHA 2022년 11월 11일
How would I put the following code in a in script function with a function name calc_pi(n).
count = 0;
for i = 1:N
u = rand(1,2);
if u(1)^2+u(2)^2<=1
count = count+1;
end
end
pi_est = count/N*4
  댓글 수: 1
Dyuman Joshi
Dyuman Joshi 2022년 11월 11일
function pi_est = calc_pi(N)
%your code
end

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

답변 (1개)

RAGHUNATHRAJU DASHARATHA
RAGHUNATHRAJU DASHARATHA 2022년 11월 11일
As per my understanding you want to write your code into a function .
I will be demonstrating it using your code as example below.
a=calc_pi(10)
a = 2.8000
function pi_est=calc_pi(N)
count = 0;
for i = 1:N
u = rand(1,2);
if u(1)^2+u(2)^2<=1
count = count+1;
end
end
pi_est = count/N*4;
end
To know more about functions go through this link

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by