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

113 Ansichten (letzte 30 Tage)
Lillian Rigoli
Lillian Rigoli am 30 Mär. 2020
Beantwortet: Steven Lord am 8 Okt. 2021
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.
I've attached the cell array here.
Thank you.

Antworten (4)

Tommy
Tommy am 30 Mär. 2020
Bearbeitet: Tommy am 30 Mär. 2020
You can try
tad = strcmp(tad,'True')

Lillian Rigoli
Lillian Rigoli am 30 Mär. 2020
better answer from stack overflow:
f = zeros(size(tad));
f(strcmp(tad,'True')) = 1;

Lillian Rigoli
Lillian Rigoli am 30 Mär. 2020
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};

Steven Lord
Steven Lord am 8 Okt. 2021
s = {'true', 'false'};
C = s(randi(numel(s), 5, 5))
C = 5×5 cell array
{'true' } {'false'} {'false'} {'true' } {'true' } {'false'} {'false'} {'true' } {'false'} {'false'} {'true' } {'false'} {'false'} {'false'} {'true' } {'true' } {'false'} {'false'} {'true' } {'true' } {'true' } {'false'} {'true' } {'true' } {'true' }
L = matches(C, 'true')
L = 5×5 logical array
1 0 0 1 1 0 0 1 0 0 1 0 0 0 1 1 0 0 1 1 1 0 1 1 1
This same works if you wanted to use a string array.
ST = string(C)
ST = 5×5 string array
"true" "false" "false" "true" "true" "false" "false" "true" "false" "false" "true" "false" "false" "false" "true" "true" "false" "false" "true" "true" "true" "false" "true" "true" "true"
LST = matches(ST, 'true')
LST = 5×5 logical array
1 0 0 1 1 0 0 1 0 0 1 0 0 0 1 1 0 0 1 1 1 0 1 1 1

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Produkte


Version

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by