str={'HA2.hdhashasdh' 'HA33.dskljdasjkdajkls' 'hh' 'HA80.djklasjdjklads' 'HA81.djkhadsh' 'HA245.fsaldjajdalsj' 'er'} list=[2,81,245] n=regexp(str,'(?<=HA)\d+\>','match','once') id=str2double(n) out=ismember(id,list)
how to find strings of varying length within longer strings
6 次查看(过去 30 天)
显示 更早的评论
I have a cell array where the first row of each column is a long string that always starts with "HA", then a number, and then more text.
For example:
HA2.hdhashasdh HA33.dskljdasjkdajkls HA80.djklasjdjklads HA81.djkhadsh HA245.fsaldjajdalsj
Then I have a vector with some of the numbers that come after 'HA'
list = [2, 81, 245]
I want to make a loop that for each string of my cell array, finds whether it starts with 'HA[one of the numbers in my list]', and returns 1 if it does and 0 if it doesn't.
I've tried to use strncmp, but there were some problems.
This is the loop I was using:
counter = 1
for i=1:length(myArray(1, :))
question = myArray(1, i); %the string I'm currently looking at
num = list(counter); %the question number
name = strcat('HA', num2str(num)); %the name of the question (e.g. HA42)
if strncmp(name, question, 4) == 1
question
name
counter = counter +1;
end
end
The problem is that 'name' is not always the same length, since the numbers in my list are 2, 80 and 245. So if I do strncmp(name, question, 4) or strncmp(name, question, 5), it always returns 0, but if I do strncmp(name, question, 3) it can return 1 even though it's wrong: for example if name is HA81, it will return 1 once it's on question HA80.jdfdskljf.
I wanted to know if there is another function to do this or any way I could make it work. Let me know if anything wasn't clear (I'm still newish to Matlab) Thanks!
0 个评论
采纳的回答
Azzi Abdelmalek
2015-7-8
编辑:Azzi Abdelmalek
2015-7-8
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!