フィルターのクリア

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 Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by