Water Filtration Problem for a class

I need to find the minimum number of stages that are needed to remove 99% of the initial impurity level of water.
I have a FOR loop set up to due the filtration like so:
for n = 1:21
n_stage(n) = n-1:
y(n) = (1/3)^(n-1);
if (y(n) <= 0.01) Here's where my issues start.
n_1p(n) = n_stage(n);
y_1p(n) = y(n);
end
end
fprintf('Minimum number of stage for 99%% filtration = %d, impurity level = %f\n',n_1p,y_1p);
#1: I'm getting two many answers because I'm not sure how to get the IF statement to stop.
#2: When it prints, it doesn't print the filtration stage (n_1p) nor the impurity level (y_1p) as would expect.
My programming skills are kinda lackluster. This is for a class I'm taking to help with said skills. Any help would be greatly appreciated.

6 Comments

Follow up question: should I move the IF statement out of the FOR loop?
You should use
break
to exit a loop early.
or use a while loop.
Joel Handy
Joel Handy on 19 Jul 2019
Edited: Joel Handy on 19 Jul 2019
In regards to your second question, what doesnt print as expected? Is it more than the fact that you have multiple n_1p and y_1 values?
In regards to the first, since this is homework specifically to work on improving coding skills, I dont want to just give you the answer (and I won't mention that you can do this without a loop at all in 3 lines of code). However, if computing all values is actually important, I will point out two things.
1) there is no reason your loop can't count down, i.e. for n = 21:1
2) You don't need to save more than one n_1p or y_1 (i.e. you don't need to index into them). You just want the values associated with the smallest value of n that meets conditions. So why not just overwrite them each time you find a better answer?
If you just need to find the desired values of n_1p and y_1 and dont care about computing all the other values, then yeah just use a break statement or a while loop instead of a for loop as suggested.
Note: the syntax for counting down would be 21:-1:1
Troy Brown
Troy Brown on 19 Jul 2019
Edited: Troy Brown on 19 Jul 2019
Thanks for the help folks. In the end, one of you said something that sparked some recollection back to the lecture notes. I ended up using "find".
ind = find(y <= 0.01);
n_1p = ind(1,1)-1;
I then altered my "fprintf" line a bit and everything worked like a charm.
Thanks again!!

Sign in to comment.

Answers (0)

Products

Asked:

on 18 Jul 2019

Edited:

on 19 Jul 2019

Community Treasure Hunt

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

Start Hunting!