Indexing String Structure Fields

10 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2023-10-5
移动:Stephen23 2023-10-5
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);

请先登录,再进行评论。

采纳的回答

Calum
Calum 2023-10-5
Never mind! Solved this using a simple strcmp function - hopefully this helps anyone else with a similar problem.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Problem-Based Optimization Setup 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by