필터 지우기
필터 지우기

for loops and if else for matrices

조회 수: 1 (최근 30일)
David Phung
David Phung 2014년 11월 2일
댓글: David Phung 2014년 11월 3일
My homework question says that theres a file called pipe.dat with a matrix inside [4.64 15.30; 5.21 15.36; 4.79 15.39]. The weight is supposed to be between 4.5 and 5.1, inclusive, and the length is supposed to be between 15.3 and 15.4, inclusive. I'm supposed to write a script that will count how many 'rejects' there are. A reject is any piece of pipe that has an invalid weight and/or length.
Here is my code:
load pipe.dat
temp1=0;
pipe
for i=1:3
if pipe(i,1)>=4.5 && pipe (i,1) <= 5.1 || pipe(i,2) >= 15.3 && pipe(i,2)<=15.4
x=0;
else
x=1;
newnum=temp1+x;
end
end
x
I'm not really sure how to tackle this problem. I've had a couple ideas, such as a nested if else statement.
load pipe.dat
temp1=0;
for i=1:3
if pipe(i,1)>=4.5 && pipe (i,1) <= 5.1
x=0;
if pipe(i,2) >= 15.3 && pipe(i,2)<=15.4
x=0;
else
x=1;
end
end
end
x
But Im not sure how to tackle this problem.

채택된 답변

Geoff Hayes
Geoff Hayes 2014년 11월 2일
David - you won't need a nested if statement, just an if and an elseif - the first to to check to see if the pipe weight is invalid, and the second to check if the pipe length is invalid. If either condition is true, then you would increment your number of rejects counter.
load pipe.mat;
numRejects = 0;
for k=1:size(pipe,1)
% check the weight
if pipe(k,1)<4.5 || pipe(k,1)>5.1
numRejects = numRejects + 1;
% check the length
elseif pipe(k,2)<15.3 || pipe(k,2)>15.4
numRejects = numRejects + 1;
end
end
  댓글 수: 1
David Phung
David Phung 2014년 11월 3일
OHHH! That makes so much sense. If the first column is a reject, then it would just skip checking the next one. Thank you so much!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by