Giacomo Brunetta
Giacomo Brunetta

Reputation: 1567

Cell to Char in MATLAB doesn't work

I have used this code to read data from a plaintext file:

[race sex age namef] = textread('Fusion.txt', '%s %s %d %s');

I convert race from cell to char using: race = char(race); to do a string comparison (if(strcmp(race(k),'W')==1)) and it works as expected. I also need to namef to char but when I do, MATLAB returns 0 for every element of namef.

Here is a sample of my file:

W   M   50  00001_930831_fb_a.ppm
W   M   30  00002_930831_fa.ppm
W   M   30  00002_930831_fb.ppm
W   M   30  00002_931230_fa.ppm
W   M   30  00002_931230_fb.ppm
W   M   31  00002_940128_fa.ppm
W   M   31  00002_940128_fb.ppm

Why is this happening?

Upvotes: 1

Views: 256

Answers (2)

zeeMonkeez
zeeMonkeez

Reputation: 5157

From your question it is not clear whether conversion to char is necessary later on. For what you want to do, it is OK to compare to the individual elements of the cells race or namef:

strcmp(race{k}, 'W')
strcmp(named{k}, '00002_930831_fa.ppm')

Since strcmp operates on cell arrays of strings as well, you can also do things such as strcmp(race, 'W').

Upvotes: 2

Since what you're doing should work fine, you're probably missing one thing: the last column in your file has multiple characters, so you need to access the whole row of the resulting string matrix, rather than a single element:

race = char(race);   %// cell to character array of size [N,1]
namef = char(namef); %// cell to character array of size [N,M], padding added
for k=1:size(race,1)
   condition_col1 = strcmp(race(k),'W')==1;
   condition_col4 = strcmp(strtrim(namef(k,:)),'00002_930831_fa.ppm');
   %// ... code goes here
end

If you use namef(k), you'll get the first character of each row, i.e. '0'. So namef(k,:) is my main point.

Also note that I added strtrim to the condition: turning to a character array will pad the fields to the length of the longest element (since matrices have to be rectangular).

Upvotes: 2

Related Questions