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!