Search code examples
matlabrowcell

Extracting rows from a cell vector


This is a really simple question, but I can't believe how stuck I am.

I have a file where each column is a different format. Some are string, some are int. By using textscan I can get the file into MATLAB as a vector of cells.

What I want to do is create a new matrix where only cats under age 10 are in.

Animal Age
Cat 11
Dog 5
Cat 2
Dog 11
Cat 16
Cat 3

This wouldn't be a problem if it wasn't for the fact that they're in their individual cells. A{1} gives me a list of animals, A{2} gives me a list of ages. If it can be solved by not using textscan that's an option as well, as the way to read the file doesn't matter much.


Solution

  • Here is how i would do it

     FileId2=fopen('Animals.txt')
     title=textscan(FileId2,'%s %s',1);   % this reads only the first line 
     data==textscan(FileId2,'%s %d');     % reads the rest of the file and stores them in string and in
     Cat=strcmp(D{1},'Cat');              % looks for Animal of type cat
     Age=data{2};                         % gets the age of the animal
     Ageofcats=Age(Cat);                  % get the age of cats 
     % and then you just find what you want
     find(Ageofcats<10);