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

カテゴリ

Find more on Multicore Processor Targets in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by