Filter löschen
Filter löschen

for loops and if else for matrices

1 Ansicht (letzte 30 Tage)
David Phung
David Phung am 2 Nov. 2014
Kommentiert: David Phung am 3 Nov. 2014
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.

Akzeptierte Antwort

Geoff Hayes
Geoff Hayes am 2 Nov. 2014
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 Kommentar
David Phung
David Phung am 3 Nov. 2014
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!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by