How to get rid of for loop?

2 vues (au cours des 30 derniers jours)
Yen Tien Yap
Yen Tien Yap le 21 Juin 2021
Modifié(e) : SALAH ALRABEEI le 21 Juin 2021
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 commentaire
KSSV
KSSV le 21 Juin 2021
What are f, g functions?

Connectez-vous pour commenter.

Réponses (1)

SALAH ALRABEEI
SALAH ALRABEEI le 21 Juin 2021
Modifié(e) : SALAH ALRABEEI le 21 Juin 2021
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

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by