How to Get one Property of a Structure Array Using a Property on the Same Line
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Voss
2024-4-14
name = 'deuterium'; % name of the isotope you want the mass of
idx = strcmp({isotopicMasses.name},name);
mass = isotopicMasses(idx).mass;
2 个评论
更多回答(1 个)
Steven Lord
2024-4-14
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!