Indexing String Structure Fields
8 views (last 30 days)
Show older comments
Hi folks - I am trying to index a structure field to be able to create a counter based on the number of times that a specific USER input occurs in said field, but i am having some problems with the syntax I think so seeking some help!
My structure contains many fields of data, though i'm basically just trying to make a filter to be able to reduce this by size based on one field - Regions.
I have as follows:
ABV = (extractfield(CRD2020, 'Region'))';
Entries = size(ABV); % Create index for filtering structure
Entries = Entries(1);
a = input('Enter REGION ABV (e.g. UK, KSA etc..): ','s'); %(Region field contains country abvs - etc. UK, USA etc...)
for j=1:1:Entries
if CRD2020(j).Region == a
Filter(:,j)=1;
elseif CRD2020(j).Region ~= a
Filter(:,j)=0;
end
end
From here on I plan to use this filter array to reduce and concatenate the entire structure, but I keep facing an error with:
if CRD2020(j).Region == a
I thought that 'CRD2020(j).Region' would be a single value.
I have also tried:
if cellstr(CRD2020(j).Region) == a
Though the '==' operator doesn't support this.
Is there any way that i can change this to be able to tell when the exact same CHARACTER entries have been input?
Thanks in advance!
C.
1 Comment
Stephen23
on 5 Oct 2023
Moved: Stephen23
on 5 Oct 2023
The basic problem is likely that you are attempting element-wise comparison of character vectors of different sizes using EQ. That won't work.
One solution is to replace this code:
if CRD2020(j).Region == a
Filter(:,j)=1;
elseif CRD2020(j).Region ~= a
Filter(:,j)=0;
end
with this:
if strcmp(a,CRD2020(j).Region)
Filter(:,j)=1;
else
Filter(:,j)=0;
end
or even better with just this:
Filter(:,j) = strcmp(a,CRD2020(j).Region);
Note that you should simplify your code by thinking in terms of arrays (not in terms of loops like some poor low-level language). For example your whole code reduces down to e.g.|:
R = extractfield(CRD2020, 'Region');
a = input('Enter REGION ABV (e.g. UK, KSA etc..): ','s');
F = strcmp(R,a);
Accepted Answer
More Answers (0)
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!