Find the existence of a character from a struct

조회 수: 5 (최근 30일)
Asim Ismail
Asim Ismail 2017년 9월 8일
댓글: OCDER 2017년 9월 8일
There is a structure with multiple fields and one of them is LOC, for example
n=5;
for i=1:n
S(i).LOC='LL';
end
From this struct, can someone please help me to find:
1) Whether 'LL' exist in the field LOC or not?
2) And how many times it is repeated?
(Note: the above written code is not what Im working on, its just to give some idea.)

채택된 답변

Stephen23
Stephen23 2017년 9월 8일
편집: Stephen23 2017년 9월 8일
Using a comma-separated list and strcmp makes this very simple:
>> S(1).LOC = 'LL';
>> S(2).LOC = 'X';
>> S(3).LOC = 'LL';
>> S(4).LOC = 'LL';
>> S(5).LOC = 'X';
>> strcmp({S.LOC},'LL') % the existence
ans =
1 0 1 1 0
>> nnz(strcmp({S.LOC},'LL')) % the number
ans = 3
or use strfind if 'LL' can be inside a longer string.
  댓글 수: 4
Asim Ismail
Asim Ismail 2017년 9월 8일
Thats what I was asking for, Thanks a lot again
OCDER
OCDER 2017년 9월 8일
Cool solution!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

OCDER
OCDER 2017년 9월 8일
편집: OCDER 2017년 9월 8일
I think this works. Not the most efficient, but gets the job done.
n=5;
for i=1:n
S(i).LOC='LL';
end
FoundLL = 0; %Counts how many LL's there in in S structure array
for j = 1:length(S) %Go over every structure in S
Fields = fieldnames(S(j)); %Find the fields in this structure
for k = 1:length(Fields) %Go over every field in S
if strcmp(Fields{k}, 'LOC') %If you have the LOC field name
CurValue = S(j).(Fields{k}); %Get the value of this field
if ~isempty(CurValue) && ischar(CurValue) && strcmp(CurValue, 'LL')
FoundLL = FoundLL + 1;
end
end
end
end
fprintf('Found this many "LL" in "LOC" field of structure S: %d\n', FoundLL)
  댓글 수: 3
Asim Ismail
Asim Ismail 2017년 9월 8일
Thank you @Donald Lee, you actually combined both my questions into this single code. I wanted to do them separately. Anyway how to check just the existence of 'LL'?
OCDER
OCDER 2017년 9월 8일
Yup, matlab if and for are slow.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by