Replacing a numberless string in matrix with a number
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello,
I have a matrix that contains a column with participants' gender written as strings ("female" vs" "male").
I would like to change females to 1 and males to 0. How would I do that?
Thank you!
0 commentaires
Réponses (2)
Stephen23
le 27 Jan 2021
Where V is that column:
V = ["female";"male";"female";"male";"male";"female"]
X = strcmpi(V,"female")
7 commentaires
Stephen23
le 27 Jan 2021
Modifié(e) : Stephen23
le 27 Jan 2021
For the values 1..N I would simply use the second output of ismember.
If you want to specify totally arbitrary values, then probably the easiest way would be to define a vector of those arbitrary values and then use indexing (e.g. the second output of ismember) to select from that vector.
You will find num2cell useful for both of these.
Steven Lord
le 27 Jan 2021
I would likely use a string array.
colors = ["green"; "blue"; "yellow"; "purple"];
% Make some sample data
ind = randi(numel(colors), 10, 1);
arrayOfColors = colors(ind);
whichColor = NaN(size(arrayOfColors));
for c = 1:numel(colors)
whichColor(arrayOfColors == colors(c)) = c;
end
% Display results side by side
results = table(ind, arrayOfColors, whichColor)
This also works if arrayOfColors was a categorical array, though for a categorical array there's an easier way to report which element of the valueset was used to generate each element of the categorical array by just using the double function.
colorCats = categorical(arrayOfColors, colors);
results.colorCats = colorCats;
results.whichCat = double(colorCats)
all(whichColor == ind)
all(results.whichCat == ind)
1 commentaire
Stephen23
le 27 Jan 2021
Without the loop:
[~,whichColor] = ismember(arrayOfColors,colors)
Voir également
Catégories
En savoir plus sur Matrices and Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!