How to ask a user for an input for once ?

조회 수: 2 (최근 30일)
Osama Al-Shalali
Osama Al-Shalali 2020년 2월 3일
답변: Osama Al-Shalali 2020년 2월 5일
I am new to MATLAB and I am attempting to make a code that asks the user to input a function and then estimates the integral using Monte Carlo Method.
My problem is when I ask to enter the function, it repeats asking for the function. I only want the user to enter the function only once.
Thanks in advance for any help!
This is my code :
under = 0;
nmax = 10000;
for i=1:nmax
x = rand;
y = rand;
prompt = 'Enter your function';
z = input(prompt);
if y <= z
under = under +1;
end
end
estimated_integration =(under/nmax);
  댓글 수: 3
Osama Al-Shalali
Osama Al-Shalali 2020년 2월 3일
@Adam
In Monte Carlo Method, we need to generate pretty enough random numbers to estimate an integration.
Adam
Adam 2020년 2월 4일
But you are asking the user to input a function every time and then running a test against that. Either you want that to happen 10000 times or if you don't then don't put it in the loop.

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

채택된 답변

KSSV
KSSV 2020년 2월 4일
Put the prompt which asks for input outside the loop.
prompt = 'Enter your function';
z = input(prompt);
under = 0;
nmax = 10000;
for i=1:nmax
x = rand;
y = rand;
if y <= z
under = under +1;
end
end
estimated_integration =(under/nmax);

추가 답변 (1개)

Osama Al-Shalali
Osama Al-Shalali 2020년 2월 5일
Thanks!
all I nedded to define
syms z x;
plot(x,subs(z));

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by