find out char in cell array

2 views (last 30 days)
VISHNU DIVAKARAN PILLAI
VISHNU DIVAKARAN PILLAI on 15 Jan 2022
Edited: DGM on 15 Jan 2022
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'.

Answers (1)

DGM
DGM on 15 Jan 2022
Edited: DGM on 15 Jan 2022
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.

Tags

Community Treasure Hunt

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

Start Hunting!