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.

채택된 답변

Voss
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
Tom
Tom 2024년 4월 14일
Thank you! This was exactly what I was looking for.
Voss
Voss 2024년 4월 14일
편집: Voss 2024년 4월 14일
You're welcome! Any questions, let me know.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Steven Lord
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 = struct with fields:
carbon: [1x1 struct]
elements.carbon
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>

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

제품


릴리스

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by