0

I have text.txt which contains words and numbers.

1. I want to use "for" and "if" for cells or matrices which contain string.

d = reshape(textread('text.txt','%s','delimiter','\t'),2,2)'
if h(1,1)=='apple'
    k=1
end

This didn't work.

2. I want to do something like this.

for m=1:size(text)
   for n=1:size(text2)
       if text2(n,3) contains 'apple' (such as "My apple his, her")
          if last word of text2(n,3) is text(m,2)
             output(m,1)==text(m,2)
             output(m,2)==text(m,1)
          end
       end
   end
end

It is written in non-Matlab way but you know what I want to do.

This type of work might be easy if the text and text2 are matrices of numbers. But they are strings.

How can I perform the same thing I do for numerical matrices?

user1849133
  • 527
  • 1
  • 7
  • 18
  • 1
    Strings are arrays of characters. For example: `S = 'Hello'` then `S(end)` would be `'o'`. Use cell to store matrices of strings (See [here](http://www.mathworks.com/help/matlab/matlab_prog/cell-arrays-of-strings.html)). Instead of `d{1,1}=='apple'` use [`strcmp`](http://www.mathworks.com/help/matlab/ref/strcmp.html)`(d{1,1}, 'apple')`. – p8me Jun 12 '13 at 15:20

1 Answers1

1

I think you're looking for the string manipulation utilities. Here are a few:

% Case-sensitive comparison
strcmp('apple', 'apple') == true
strcmp('apple', 'orange') == false    

% Case-INsensitive comparison
strcmpi('apple', 'AppLe') == true
strcmpi('apple', 'orange') == false    

% Compare first N characters, case sensitive
strncmp('apple', 'apples are delicious', 5) == true   

% Compare first N characters, case INsensitive
strncmpi('apple', 'AppLes are delicious', 5) == true   

% find strings in other strings
strfind('I have apples and oranges', 'apple') 
ans =
    8    % match found at 8th character 

% find any kind of pattern in (a) string(s)
regexp(...) 

Well I'm not going to even begin on regexp...Just read doc regexp :)

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96