Make a loop to calculate molecular weight
3 views (last 30 days)
Show older comments
"Use a while loop to ask the user to enter the elemental symbols of the elements in the compound and store these in a padded character array. The user should be asked if there are any more elements to be added and the loop should continue as long as the user enters an upper or lower case y.
Use a second loop that will prompt the user to enter the atomic mass and number of atoms in the compound for each element. These should be stored in separate arrays."
Please help I can't get it to word.
2 Comments
dpb
on 15 Nov 2013
Well, haven't even seen your start at what doesn't work...show that and a specific question may elicit hints. Full solutions are rarely, if ever, forthcoming.
Answers (3)
Walter Roberson
on 17 Nov 2013
more = input('Are there more elements? y/n','s');
while strcmpi(more, 'y')
element{end+1} = input('Enter the atomic symbol: ', 's);
more = input('Are there more elements? y/n','s');
end
5 Comments
Marc
on 19 Nov 2013
I have to say that this question becomes redundant when you look at molmass() in the file exchange. The logic used in that function DOES what you are asking the user to input....
So if you want the molecular weight for C6H6 or Pt(NH3)4Cl2.... It figures out the atoms and the amounts, along with "stuff" in parenthesis...
Thus the weight percent becomes trivial...
%C in benzene = 100*6*MolMass('C')/MolMass('C6H6)
Marc
on 19 Nov 2013
I really hate doing others homework...
But... This works really well and shows one how to use recursive programming.
Next time try google...
0 Comments
Ngoc Tran
on 8 Oct 2016
I just ran into this today and this is the code that I have. I don't use a loop.
Create a container map (similar to Python's dictionary):
key = {'C','H','O'};
value = [12,1,16];
atom = containers.Map(key,value);
molecule = {'C','H','H','H','H'} %CH4
MW = sum(cellfun(@(x) atom(x), molecule))
This will go through every element in the "molecule" list, get the atom mass. You will have an array of atom mass, in this case [12 1 1 1 1], and then sum them up.
To get a more extensive key/value pair you can find .csv files online. I'm just giving an example.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!