Clear Filters
Clear Filters

How to Get one Property of a Structure Array Using a Property on the Same Line

4 views (last 30 days)
Hello all,
I'm a novice at MatLab (I'm taking a course on it), but I want to use it to be able to access atomic masses without needing to look at the back of my back for a course. I found a CSV of the atomic masses of every isotope, and I've made it into a structure array using a for loop. Basic stuff.
rawMassData = readcell('IUPAC-atomic-masses.csv');
for i=3:length(rawMassData)
isotopicMasses(i).name = rawMassData{i,1};
isotopicMasses(i).mass = rawMassData{i,2};
isotopicMasses(i).uncertainty = rawMassData{i,3};
The question I have is how do I now get the mass of a certain isotope? One field in the structure array is all the names, so I should just be able to index into the structure by name, find the line that that isotope is on, and get the mass on that same line right? I just don't know how to do that.

Accepted Answer

Voss on 14 Apr 2024
name = 'deuterium'; % name of the isotope you want the mass of
idx = strcmp({},name);
mass = isotopicMasses(idx).mass;

More Answers (1)

Steven Lord
Steven Lord on 14 Apr 2024
You could do what you described by making a non-scalar struct, each element of which has three fields, each of which has a piece of text or a number. Another approach would be to create a scalar struct, each field of which is named for an element, and which contains a struct.
elements.carbon = struct('number', 6, 'mass', 12.011)
elements = struct with fields:
carbon: [1x1 struct]
ans = struct with fields:
number: 6 mass: 12.0110
Since you're reading the data from a file, you'd need to use dynamic field names to create the field.
name = 'oxygen';
elements.(name) = struct('number', 8, 'mass', 15.999)
elements = struct with fields:
carbon: [1x1 struct] oxygen: [1x1 struct]
Alternately, since your data is tabular in nature, consider creating it as a table array rather than a struct.
names = ["carbon"; "oxygen"];
number = [6; 8];
mass = [12.011; 15.999];
elementsT = table(number, mass, RowNames = names)
elementsT = 2x2 table
number mass ______ ______ carbon 6 12.011 oxygen 8 15.999
To retrieve the data, you can use curly braces or dot notation.
elementsT{'carbon', 'mass'}
ans = 12.0110
allMasses = elementsT.mass
allMasses = 2x1
12.0110 15.9990
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>


Find more on Programming 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!