How to get rid of for loop?
3 views (last 30 days)
Show older comments
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
Answers (1)
SALAH ALRABEEI
on 21 Jun 2021
Edited: SALAH ALRABEEI
on 21 Jun 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
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!