How do you rewrite the nested if statement as a loop?

조회 수: 1 (최근 30일)
Jillian Sweatt
Jillian Sweatt 2017년 2월 2일
편집: Jan 2017년 2월 2일
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

채택된 답변

Jan
Jan 2017년 2월 2일
편집: Jan 2017년 2월 2일
Are you really sure, that you want to exclude e.g. the value -0.8 from your results?
Do you really want a for loop, although a single call to histcounts might solve this efficiently?
count = histcounts(x, -1:0.1:1)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by