for loops and if else for matrices

1 次查看(过去 30 天)
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