Borrar filtros
Borrar filtros

How to get rid of for loop?

4 visualizaciones (últimos 30 días)
Yen Tien Yap
Yen Tien Yap el 21 de Jun. de 2021
Editada: SALAH ALRABEEI el 21 de Jun. de 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 comentario
KSSV
KSSV el 21 de Jun. de 2021
What are f, g functions?

Iniciar sesión para comentar.

Respuestas (1)

SALAH ALRABEEI
SALAH ALRABEEI el 21 de Jun. de 2021
Editada: SALAH ALRABEEI el 21 de Jun. de 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

Categorías

Más información sobre Mathematics en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by