필터 지우기
필터 지우기

How to get rid of for loop?

조회 수: 2 (최근 30일)
Yen Tien Yap
Yen Tien Yap 2021년 6월 21일
편집: SALAH ALRABEEI 2021년 6월 21일
Hi, may I know how to get rid of the for loop by using logical indexing? Thnak you.
function [x_vals,y_vals,I,A]=monte_carlo_syms(x,y,f,g)
x_vals=unifrnd(0,1,[200,1]);
y_vals=unifrnd(0,1,[200,1]);
for i=1:length(x_vals)
f_val=subs(f,x,x_vals(i));
f_val=double(subs(f_val,y,y_vals(i)));
g_val=subs(g,x,x_vals(i));
g_val=double(subs(g_val,y,y_vals(i)));
if f_val> g_val
I(i,1)=true;
else
I(i,1)=false;
end
end
hold on
scatter(x_vals(I==1),y_vals(I==1),'x','g')
scatter(x_vals(I==0),y_vals(I==0),'x','r')
A=sum(I)/length(x_vals);
end
  댓글 수: 1
KSSV
KSSV 2021년 6월 21일
What are f, g functions?

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

답변 (1개)

SALAH ALRABEEI
SALAH ALRABEEI 2021년 6월 21일
편집: SALAH ALRABEEI 2021년 6월 21일
function [x_vals,y_vals,I,A]=monte_carlo_syms(x,y,f,g)
x_vals=unifrnd(0,1,[200,1]);
y_vals=unifrnd(0,1,[200,1]);
I = nan*length(x_vals);
f_val = subs(f,{x,y},{x_vals,y_vals});
g_val = subs(g,{x,y},{x_vals,y_vals});
mask = f_val> g_val;
I(mask,1)=1;
I(~mask,1)=0;
scatter(x_vals(mask),y_vals(mask),'x','g')
scatter(x_vals(~mask),y_vals(~mask),'x','r')
A=sum(I)/length(x_vals);
end

카테고리

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