Samira
Samira

Reputation: 41

How to search for a string in cell array in MATLAB by comparing it to another string?

I have tried to use strcmp but I don't know how to look through the cell arrays and output only the cell arrays with that string.

For example str='Hello'

out=["Hello", "my", "name", "is" "sam"]
out=["What", "is", "you", "name"]
out=["Hello", "my", "name", "is" "John"]

My code is as follows

while ~feof(fid)
    line=fgetl(fid)
    if isempty(line)||strncmp(line, '%',1)||~ischar(line)
        continue
    end
    fprintf(line)
    out=regexp(line, '', 'split')
end

I want to add if(str=="Hello"), only print out those arrays

output

["Hello", "my", "name", "is" "sam"]
["Hello", "my", "name", "is" "John"]

Upvotes: 1

Views: 1048

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283634

Something along the lines of

if any(strcmp('Hello', out))

should be useful.

Upvotes: 1

tqjustc
tqjustc

Reputation: 3814

use ismember() . For example, out = {'Hello', 'my', 'name', 'is', 'sam'};, then ismember(out, 'Hello') should be 1. You can check this discussion http://www.mathworks.com/matlabcentral/newsreader/view_thread/284849

By the way, out=["Hello", "my", "name", "is" "sam"] is not a representation of a cell. It should be out = {'Hello', 'my', 'name', 'is', 'sam'}

Upvotes: 1

Related Questions