Is there a function for finding the specific column number in a cell array?
27 views (last 30 days)
Show older comments
Helle everyone,
I think question is clear but, this is Matlab at all, I have a nx1 cell array and I want to know which column contains "WantedName" word. So firstly I have written a script to do this, but it takes so much time at debugging, because there are so many columns. I think there should be a function to do that like findcolumn(A, 'x'). my script that works fine for me;
names = fieldnames(EXC);
Snames = strfind(names, 'WantedName')
for k = 1:numel(Snames)
if Snames{k} == 1;
n = k
end
end
Fieldnames and 'WantedName'(s) are not corresponding word by word everytime, so I need to use strfind to find if 'WantedName' exists in a fieldname of EXC(struct). so strfind gives me cell array of names but place "1" for the column that have 'WantedName' in it. and then I need to do numel(names) times of for loop to find which column it is that having "1".
There should be a function to do that?? It is not the end of the world, script works well right now but I am curious.
0 Comments
Accepted Answer
More Answers (1)
Walter Roberson
on 18 Oct 2017
[tf, idx] = ismember('WantedName', names);
Then, if tf is true then names{idx} is 'WantedName'.
You hint that you might have several wanted names. If so then
[tf, idx] = ismember(WantedNames, names);
where WantedNames is a cell array of strings to look for in names. tf(K) tells you if WantedNames{K} was found, and if it was found then idx(K) is the position in names.
3 Comments
Walter Roberson
on 18 Oct 2017
If you have R2016b or later,
tf = startsWith(names, WantedNames)
This will return a logical array the same size as names (assuming it is a string array or cell array of character vectors) that tells you which of the entries start with something (anything) in Wantednames (which can be a character vector or string array or cell array of character vectors.)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!