to use ismember with arraycell
Show older comments
gg =
4×1 cell array
{'A' }
{'A'}
{'B' }
{'A' }
[a,b]=ismember({'A'},gg)
a =
logical
1
b =
1
is not corret..i expect 1 1 0 1
1 Comment
"is not corret.."
It is correct: the first input 'A' is definitely a member of the second input:
ismember('A',{'A','A','B','A'})
"i expect 1 1 0 1"
ismember({'A','A','B','A'},'A')
Accepted Answer
More Answers (2)
gg = {'A' ,'A','B' ,'A' }
a = cell2mat(gg)
g = zeros(1,length(a));
g(find(a=='A')) = 1
7 Comments
shamal
on 13 Oct 2024
What?
My solution is confidently correct, adequate, working good, performing sane, functioning well for numerous reasons, 1st it doesn't require hardcoding of the symbols, as you mistakenly accepted not my and not of Matt J. and not the last shortest one, another before.
There are N questions : to N answers to match, to fit finally. As any d.l. like natural system I can do of course more optimal & better if a customer is going to reward and remunerates me well.
Of course the best(shortest one) is this:
[a2, b2] = ismember(gg, {'A'})
If you are sufficiently attentive to the great details as well as I you will see, that shortest (in terms of system clock steps and memory footprint) is the solution followed after my in time and also they used ';' intracell delimeter, while in my solution the ',' intracell delimiter is more close to original and simpler.
Here is my shortened version:
gg = {'A' ,'A','B' ,'A' }
g= zeros(1,length(cell2mat(gg)))
g(find( cell2mat(gg) == 'A') ) = 1
Please let me know which way to help optimally as per custom requirements, what to keep doing.
clc
clear all
close all
%% Inputs ( from a methode ):
ex = 'STA';
dd = { 'STA', 'STAT', 'STA', 'STATT' } ;
%% Detection module:
% contains(dd, 'STA') is not yet implemented as built-in in TCE Octave
if length(ex)>1
strcmp(dd,ex)
else
a = cell2mat(dd);
g = zeros(1,length(a));
g(find(a==ex)) = 1
end
Both outputs are the same size as the first input.
gg = {'A'; 'A'; 'B'; 'A'};
[a1,b1]=ismember({'A'},gg)
[a2, b2] = ismember(gg, {'A'})
2 Comments
shamal
on 13 Oct 2024
Based on a revised example you posted as a comment on another answer, it looks like you're not trying to find cells in a cell array that are an exact match for a specific character. It looks like you're trying to find cells that contain that character anywhere inside the word they contain. If that is correct:
gg = { 'STA' , 'STAT' , 'STA' , 'STATT' }
contains(gg, 'A')
gg{3} = 'STEM' % Replace one of the words with one not containing 'A'
contains(gg, 'A')
Or you could use other string related functions instead of contains. Some examples include startsWith and endsWith.
Categories
Find more on Lengths and Angles in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!