How do you rewrite the nested if statement as a loop?
Mostrar comentarios más antiguos
clear; close all
n = 4000;
% (A) Use rand to generate randomly distributed points:
Rand_Number = rand(n, 2);
x = Rand_Number(:,1)*2-1;
y = Rand_Number(:,2)*2-1;
hold on
figure(1)
subplot(3,1,1)
plot(x,y,'r.')
title('Random Points Generated Using "rand"')
xlabel('x')
ylabel('y')
subplot(3,1,2)
count = zeros(1,20);
for i=1:length(x)
if x(i) >= -1 && x(i) <= -0.9
count(1) = count(1)+1;
elseif x(i) >-0.9 && x(i)<-0.8
count(2) = count(2)+1;
elseif x(i)>-0.8 && x(i)<-0.7
count(3) = count(3)+1;
elseif x(i)>-0.7 && x(i)<-0.6
count(4) = count(4)+1;
elseif x(i)>-0.6 && x(i)<-0.5
count(5) = count(5)+1;
elseif x(i)>-0.5 && x(i)<-0.4
count(6) = count(6)+1;
elseif x(i)>-0.4 && x(i)<-0.3
count(7) = count(7)+1;
elseif x(i)>-0.3 && x(i)<-0.2
count(8) = count(8)+1;
elseif x(i)>-0.2 && x(i)<-0.1
count(9) = count(9)+1;
elseif x(i)>-0.1 && x(i)<0
count(10) = count(10)+1;
elseif x(i)>0 && x(i)<0.1
count(11) = count(11)+1;
elseif x(i)>0.1 && x(i)<0.2
count(12) = count(12)+1;
elseif x(i)>0.2 && x(i)<0.3
count(13) = count(13)+1;
elseif x(i)>0.3 && x(i)<0.4
count(14) = count(14)+1;
elseif x(i)>0.4 && x(i)<0.5
count(15) = count(15)+1;
elseif x(i)>0.5 && x(i)<0.6
count(16) = count(16)+1;
elseif x(i)>0.6 && x(i)<0.7
count(17) = count(17)+1;
elseif x(i)>0.7 && x(i)<0.8
count(18) = count(18)+1;
elseif x(i)>0.8 && x(i)<0.9
count(19) = count(19)+1;
elseif x(i)>0.9 && x(i)<=1
count(20) = count(20)+1;
end
end
X=-.95:.1:1;
bar(X,count)
title('Distribution of Points')
xlabel('x')
ylabel('y')
subplot(3,1,3)
hist(x)
title('Histogram of Points')
xlabel('x')
ylabel('y')
hold off
end
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!