How to Get one Property of a Structure Array Using a Property on the Same Line
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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};
end
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.
1 Kommentar
Akzeptierte Antwort
Voss
am 14 Apr. 2024
name = 'deuterium'; % name of the isotope you want the mass of
idx = strcmp({isotopicMasses.name},name);
mass = isotopicMasses(idx).mass;
2 Kommentare
Weitere Antworten (1)
Steven Lord
am 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.carbon
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)
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)
To retrieve the data, you can use curly braces or dot notation.
elementsT{'carbon', 'mass'}
allMasses = elementsT.mass
0 Kommentare
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!