search for specific values in structure in matlab

In MATLAB, you can search for specific values in a structure using the "find" and "strcmp" functions.

Assuming that you have a structure named myStruct with field names "name" and "age", and you want to find all entries in the structure where the "name" is "John", you can use the following code:

main.m
% Create a sample structure
myStruct(1).name = 'John';
myStruct(1).age = 25;
myStruct(2).name = 'Mary';
myStruct(2).age = 30;
myStruct(3).name = 'John';
myStruct(3).age = 35;

% Find all entries with name "John"
idx = find(strcmp({myStruct.name},'John'));

% Display the results
disp(myStruct(idx));
300 chars
14 lines

This code will output the two entries in the myStruct structure where the "name" is "John":

main.m
name: 'John'
 age: 25

name: 'John'
 age: 35
45 chars
6 lines

Alternatively, if you want to search for a specific age value, you can modify the code to use the "==" operator instead of "strcmp". For example, the following code will find all entries in the myStruct structure where the "age" field is 30:

main.m
% Find all entries with age = 30
idx = find([myStruct.age]==30);

% Display the results
disp(myStruct(idx));
109 chars
6 lines

This code will output the single entry in the myStruct structure where the "age" field is 30:

main.m
name: 'Mary'
 age: 30
22 chars
3 lines

related categories

gistlibby LogSnag