Help using While loop
1 view (last 30 days)
Show older comments
Charles Duggan
on 1 May 2019
Commented: Charles Duggan
on 5 May 2019
Hello. As an extra credit for my MatLab class, I must make a program that uses both For loop and While loop to take user input into a function, and return with a final value (see attached code). I can make it run logically without a while loop. Im looking for an idea of where I should put the While loop and what it should be looking for.
clc
clear
Na = input('Enter Sodium Oxide Content (%)');
Ca = input('Enter Calcium Oxide Content (%)');
Si = input('Enter Silicon Oxide Content (%)');
Batch = [Na,Ca,Si];
p = input('Batch weight in grams');
MM = [61.977;56.077;60.083]; %Provided MolarMass Values
TG = [1.710;1.780;1.000]; %Provided Thermo Values
%--------------------------------------------------------------------
if sum(Batch) <100 %Ensures It is 100%
disp('Error - Total Content is Not 100%')
disp(sum(Batch))
elseif sum(Batch)>100 %Ensures it is 100%
disp('Error - Total Content is Not 100%')
disp(sum(Batch))
end
if p <= 0 %Ensures the Batch isnt a negative weight
disp('Batch Weight is Invalid - Check for negative value')
end
if sum(Batch) == 100 && p > 0 %If 100% and Pos. Batch value then it does the calculations
W = Na*MM(1,1,1);
Q = Ca*MM(2,1,1);
E = Si*MM(3,1,1);
NewB = [W,Q,E];
FWB1 = (W/sum(NewB))*p*TG(1,1,1);
FWB2 = (Q/sum(NewB))*p*TG(2,1,1);
FWB3 = (E/sum(NewB))*p*TG(3,1,1);
R = [FWB1,FWB2,FWB3];
Y = sum(R);
end
disp(FWB1)
disp(FWB2)
disp(FWB3)
disp('Total Batch Weight (g):')
disp(Y)
Please let me know any ideas or reccomendations of what to do here
Final note - I tried to make the while loop use the "sum(Batch) == 100 && p > 0" but that doesnt logically make sense nor work in this"*
0 Comments
Accepted Answer
Geoff Hayes
on 2 May 2019
Charles - I think that you could use a while or for loop on this code
W = Na*MM(1,1,1);
Q = Ca*MM(2,1,1);
E = Si*MM(3,1,1);
NewB = [W,Q,E];
FWB1 = (W/sum(NewB))*p*TG(1,1,1);
FWB2 = (Q/sum(NewB))*p*TG(2,1,1);
FWB3 = (E/sum(NewB))*p*TG(3,1,1);
Note how you extract the first, second, and third element from MM for three different calculations. This suggests that a loop could be used here especially since you have already put your Na, Ca, and Si into the Batch array. For example,
NewB = zeros(length(MM),1);
for k = 1:3
NewB(k) = Batch(k) * MM(k);
end
Then do something similar for the FW calculations.
More Answers (0)
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!