Indexing String Structure Fields

조회 수: 6 (최근 30일)
Calum
Calum 2023년 10월 5일
이동: Stephen23 2023년 10월 5일
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에서 Performance and Memory에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by