for loops and if else for matrices
2 次查看(过去 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.
0 个评论
采纳的回答
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 General Applications 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!