I am not certain what you are doing, or what the requirements of what is probably a homework problem are.
First, ‘sEggs’ and the others that you calculate in the beginning are vectors of logical subscripts, so you need to use them as such.
Second, if-else statements work such that the first statement that is true will then do what that condition requires and then exit the if block. See the Description section of the if,elseif,else documentation. I changed your code slightly to make it do what I believe you want it to do:
weightEggs = randi([45 85],1,100);
sEggs = weightEggs <= 53;
mEggs = (weightEggs > 53) & (weightEggs <= 63);
lEggs = (weightEggs > 63) & (weightEggs <= 73);
xlEggs = weightEggs > 73;
if any(weightEggs <= 53)
disp([ num2str(weightEggs(sEggs)) ' are small eggs.' ])
end
if any(weightEggs > 53 | weightEggs <= 63)
disp([ num2str(weightEggs(mEggs)) ' are medium eggs.' ])
end
if any(weightEggs > 63 | weightEggs <= 73)
disp([ num2str(weightEggs(lEggs)) ' are large eggs.' ])
end
if any(weightEggs > 73)
disp([ num2str(weightEggs(xlEggs)) ' are extra-large eggs.' ])
end
Also see the documentation for the any function. Make appropriate changes to get the result you want.
Best Answer