Return rows (not just row number)

9 次查看(过去 30 天)
Hello
I would be happy if anyone could help me with following problem.
I have an text (or excel) file which is in the following form (or course in reality it is in larger form but anyway the basic idea is):
And now I would like to find all the 'Cat'-rows and return that row and the following row.
So in the end my answer should be
And I don't even know how to begin. Could anyone help?

采纳的回答

Ingrid
Ingrid 2016-1-29
just use strfind or strcmp to find the indices
varNames = var(:,1);
IndexC = strfind(varNames, 'Cat');
Index = find(not(cellfun('isempty', IndexC)));
Index = sort([Index; Index+1]);
extracted = var(Index,:);

更多回答(3 个)

Walter Roberson
Walter Roberson 2016-1-29
match = ismember(var(:,1), 'Cat');
extended_match = match | [true; match(1:end-1)]; %row and following row; and also header
extracted = var(extended_match, :);

Snowfall
Snowfall 2016-1-29
编辑:Snowfall 2016-1-29
Thank you, these help me a lot :)
But it also raised a new question... What should I do if i want to find a word which contains word 'Cat'. For example in that table (above) I would have words 'TigerCat' and 'LionCat' instead of just 'Cat' (like in previous question) and I would like to return all rows which contains 'Cat'?
Is Matlab capable of doing that?
  2 个评论
Walter Roberson
Walter Roberson 2016-1-30
Ingrid's strfind solution will find 'Cat' anywhere in the string. It is, though, case sensitive. If you want a case-insensitive solution then you could use Ingrid's solution modified slightly to
IndexC = strfind(lower(varNames), lower('Cat'));
The function I used, ismember(), does not extend to locating strings within other strings. I would probably modify my solution to
match = ~cellfun(@isempty,regexpi(varNames,'Cat'));
Snowfall
Snowfall 2016-2-3
Thank you for your answer. I begin to try these in practice.

请先登录,再进行评论。


Snowfall
Snowfall 2016-2-5
How about a case where I would like to find all words which do not include 'Cat' or 'Guinea pig'?
  2 个评论
Ingrid
Ingrid 2016-2-5
it is better if you make a new question for this as this one already has an accepted answer so you are less likely to get an answer but here goes:
varNames = var(:,1);
IndexCat = strfind(varNames, 'Cat');
Index1 = find(not(cellfun('isempty', IndexCat)));
IndexPig = strfind(varNames,'Guinea pig');
Index2= find(not(cellfun('isempty',IndexPig)));
Index =~(Index1|Index2);
Index = sort([Index; Index+1]);
extracted = var(Index,:);
Snowfall
Snowfall 2016-2-7
编辑:Snowfall 2016-2-7
Ok, thank you for your answer. Next time I'll write a new question :)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by