how to find the molecular weight of an object in matlab

To find the molecular weight of a chemical compound in Matlab, you can use the following code:

main.m
% Define the chemical formula of the compound
formula = 'H2O';

% Define the atomic weights of each element
atomicWeights = [1.0079, 15.999];

% Split the formula into its elemental components
elements = regexp(formula, '([A-Z][a-z]?\d*)', 'match');

% Calculate the molecular weight
molecularWeight = 0;
for i = 1:length(elements)
    % Extract the element symbol and the number of atoms
    [element, numAtoms] = regexp(elements{i}, '([A-Z][a-z]?)(\d*)', 'tokens');
    element = element{1}{1};
    if isempty(numAtoms{1}{2})
        numAtoms = 1;
    else
        numAtoms = str2double(numAtoms{1}{2});
    end
    % Find the atomic weight of the element
    atomicWeight = atomicWeights(strncmpi(element, {'H', 'C', 'N', 'O'}, 1));
    % Add the contribution to the molecular weight
    molecularWeight = molecularWeight + numAtoms*atomicWeight;
end

disp(['The molecular weight of ' formula ' is ' num2str(molecularWeight) ' g/mol.'])
940 chars
28 lines

This code defines the chemical formula of the compound, the atomic weights of each element, and splits the formula into its elemental components. It then iterates over each element in the formula, calculating its contribution to the molecular weight. The final result is printed to the console.

Note that the atomic weights used in this code are taken from the periodic table and are in units of atomic mass units (amu). To convert to grams per mole (g/mol), you need to multiply by the molar mass constant, which is approximately 1 g/mol per amu.

gistlibby LogSnag