AMcNall
AMcNall

Reputation: 529

Matlab - Filter Struct array using multiple strings

I have a large struct array

Month = 
1x10131 struct array with fields:
name
date
bytes
isdir
datenum

From which I need to filter a number of rows using an array (in the name field).

I was previously using

result = Month([string here])

But I just noticed that is not doing what I wanted at all, it seems to be filtering in someway, but not in anyway I desired.

I have the above struct array, and 4 strings (name) in a char array. I need an output of the four matched names with the associated date, bytes, isdir and datenum from the original array..

Upvotes: 0

Views: 1253

Answers (1)

user2271770
user2271770

Reputation:

Here's a little code snippet that will put in SelectedMonth the structs that have the name field matching one of the entries in cell array SelectedName:

SelectedName  = {'n1', 'n2', 'n3', 'n4'};  % change to your values
SelectedIndex = cellfun(@(x) any(strcmp(x, SelectedName)), {Month.name});
SelectedMonth = Month(SelectedIndex);

From here on you may extract wjhatever information you want from the struct array SelectedMonth. Please note that the string comparison is case sensitive, so be careful about the case of the names.

Upvotes: 4

Related Questions