Extracting value from Name-Value pairs using the Name string

2 次查看(过去 30 天)
Let's say I have a variable called 'test'. test is a 1x2 struct array with 2 fields - Name and Value.
test =
1×2 struct array with fields:
Name
Value
When I open the variable 'test', this is how it looks. Each of the fields have 2 values (2 pairs of name-value pair)
How can I extract just the value of the name 'long_name' without using positional index?
Using positional index, I can do it using the following code
test(2).Value
But I want to use the name string 'long_name' to find the corresponding value, as the 'long_name' may not always be at the 2nd position in other variables like test.
Any leads on how I could do that?
Thanks!

采纳的回答

Cris LaPierre
Cris LaPierre 2021-9-14
ind = strcmp({test.Name},'long_name');
test(ind).Value

更多回答(1 个)

Steven Lord
Steven Lord 2021-9-14
test = struct('units', {'degrees_east', 'degrees_north'}, ...
'long_name', {'longitude', 'latitude'})
test = 1×2 struct array with fields:
units long_name
theNames = {test.long_name};
findSpecificName = ismember(theNames, 'longitude');
T = test(findSpecificName)
T = struct with fields:
units: 'degrees_east' long_name: 'longitude'
q = test(ismember(theNames, 'latitude')).units
q = 'degrees_north'

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by