Replace certain row values in a cell based on a condition

I have a 1600x1 cell, where every row contains one of two strings - A or B.
I am trying to replace them with doubles (A with 0, B with 1), but having some difficulties. The '==' operator does not work because it is a cell. My attempts to convert it to a vector (via cell2mat) failed with the very peculiar:
Error using cat
Dimensions of arrays being concatenated are not consistent.
Error in cell2mat (line 83)
m{n} = cat(1,c{:,n});
Error in my_file (line 149)
col = cell2mat(col)
My questions are two (of which only the first is important, second is merely curiosity):
1 - How do I replace the A and B strings in my 1600x1 cell with 0 and 1 respectively?
2 - Why does cell2mat fail when attempting to convert a Nx1 cell?

 Réponse acceptée

C = {'stringA'; 'stringA'; 'stringB'; 'stringA'}
C = 4×1 cell array
{'stringA'} {'stringA'} {'stringB'} {'stringA'}
C_logical = strcmp(C,'stringB') % logical
C_logical = 4×1 logical array
0 0 1 0
C_double = double(strcmp(C,'stringB')) % double
C_double = 4×1
0 0 1 0
cell2mat(C) % works because all char vectors contained in C are the same length
ans = 4×7 char array
'stringA' 'stringA' 'stringB' 'stringA'
C{3} = 'stringBB'
C = 4×1 cell array
{'stringA' } {'stringA' } {'stringBB'} {'stringA' }
cell2mat(C) % does not work because not all char vectors contained in C are the same length
Error using cat
Dimensions of arrays being concatenated are not consistent.

Error in cell2mat (line 83)
m{n} = cat(1,c{:,n});

2 commentaires

Thanks a lot, this worked great!
However, that cell was previously a column of a table, and I am now facing some difficulties with returning the resulting logical or double array into that table.
I get "Right hand side of an assignment into a table must be another table or a cell array", and when I try to convert the array to a cell I get greeted with "Conversion to cell from double/logical is not possible".
Do you maybe have a tip on how can I add that array into the table?
Voss
Voss le 24 Juin 2022
Modifié(e) : Voss le 24 Juin 2022
T = table({'stringA'; 'stringA'; 'stringB'; 'stringA'},[1;2;3;4])
T = 4×2 table
Var1 Var2 ___________ ____ {'stringA'} 1 {'stringA'} 2 {'stringB'} 3 {'stringA'} 4
% T.Var1 = strcmp(T.Var1,'stringB') % logical
T.Var1 = double(strcmp(T.Var1,'stringB')) % double
T = 4×2 table
Var1 Var2 ____ ____ 0 1 0 2 1 3 0 4

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Distribution Plots dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by