Convert cell of 'True' and 'False' values to a numeric array of 1s and 0s

Viewed 86

i have a 6432 x 1 cell containing values of either 'True' or 'False'. I'm trying to convert the cell to a numeric array with a value of 0 for False and 1 for True. I must be missing an obvious solution, but I feel like I've tried everything. Thank you.

4 Answers

A little out of the box solution, which should be faster than comparing the same strings thousands of times:

t = sum(char(s),2) < 485

Explanation

char(s) makes a char-array out of the cell array of strings.

sum creates a checksum.

If the checksum is smaller than 500 (actually 481, to be exact), it must be 'true'. The checksum of 'false' is 523. For that matter, as the capital letter variant 'True' leads to 448 and 'False' to 491, something around 485 would be a suitable threshold value.

If your cell is called s, you can do this:

t = zeros(size(s));
t(strcmp(s,'True')) = 1;

Ok i found a way that works but seems inefficient? If anyone knows a better solution it'd be much appreciated.

t = find(strcmp(tad, 'True'));
tad(t,:) = {1};
f = find(strcmp(tad, 'False'));
tad(f,:) = {0}

You can also use cellfun and only compare the first character for better performance (However, it may be slower for using cellfun).

t = double(cellfun(@(x) x(1) == 'T',s));

This is another method just for fun:

t = 5 - cellfun(@length,s);

or

t = 5 - cellfun('length',s);

Related