find out char in cell array

조회 수: 30 (최근 30일)
VISHNU DIVAKARAN PILLAI
VISHNU DIVAKARAN PILLAI 2022년 1월 15일
편집: DGM 2022년 1월 15일
for x=1:length(semifinalcode)
newtrim="("+trim_Ainstruction+")";
%k15 = strfind(semifinalcode{x},'(')
%k15 = ismember(semifinalcode{x},'(');
if semifinalcode{x}==newtrim
semifinalcode{x}={};
end
end
if k15==1
disp()
end
i tried to find out char starting with '(' and get result as true or false. and check with if condition. i tried in the above 2 way but failed while checking with if condition.semifinalcode data type is 'cell array'.

답변 (1개)

DGM
DGM 2022년 1월 15일
편집: DGM 2022년 1월 15일
If all you're trying to do is get a logical indicator of which char arrays in a cell array start with a particular character, you can use something like this example.
cellarray = {'no parentheses'; '(starts with parentheses)'; ...
'contains () parentheses'; ''};
startswithLP = cellfun(@(x) ~isempty(x) && x(1)=='(',cellarray)
startswithLP = 4×1 logical array
0 1 0 0
I'm sure there are plenty of other ways as well.
Note that this
if semifinalcode{x}==newtrim
Will result in an error if the two char vectors are not the same length. Normally you'd use strcmp() for this kind of comparison.
It's not really clear if you're intending to create a nested cell array instead of just omitting the entries.
semifinalcode{x}={}; % creates a nested empty cell array
Alternatively, you could either replace the omitted entries with empty chars or simply remove the elements completely, shortening the cell array. That way any further processing that presumes that the contents are chars won't break. Continuing with the prior example:
cellarray = {'no parentheses'; '(starts with parentheses)'; ...
'contains () parentheses'; ''};
targetphrase = 'no parentheses';
matchestarget = strcmp(cellarray,targetphrase)
matchestarget = 4×1 logical array
1 0 0 0
cellarray(matchestarget) = repmat({''},nnz(matchestarget),1) % either replace with empty char
cellarray = 4×1 cell array
{0×0 char } {'(starts with parentheses)'} {'contains () parentheses' } {0×0 char }
cellarray = cellarray(~matchestarget) % or just remove those elements entirely
cellarray = 3×1 cell array
{'(starts with parentheses)'} {'contains () parentheses' } {0×0 char }
Note that using a loop was not necessary to process the cell array. Strcmp() and many other functions handle cell arrays of chars just fine.

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by