How to modify table elements without using a for loop?

3 vues (au cours des 30 derniers jours)
Elissa
Elissa le 4 Nov 2018
Commenté : Peter Perkins le 6 Nov 2018
E.g.
% t is a table
for (yy = 1:size(t,1))
if strcmp('cat',t.animal(yy))
t.value(yy) = t.value(yy)*-1;
end
end
  1 commentaire
madhan ravi
madhan ravi le 4 Nov 2018
give a short example and upload your table

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 4 Nov 2018
Modifié(e) : Stephen23 le 4 Nov 2018
Your original idea of using strcmp was perfect, there is no need to complicate things with strings:
value = [1;2;3;4]
animal = {'cat';'dog';'cat';'dog'}
t = table(value,animal)
idx = strcmp(t.animal,'cat')
t.value(idx) = -t.value(idx)
  2 commentaires
Elissa
Elissa le 4 Nov 2018
Perfect, thanks.
Peter Perkins
Peter Perkins le 6 Nov 2018
One addition to Stephen's sol'n: if animal is representative of what your actual data look like, you should consider using a categorical variable. You would then change one line
idx = (t.animal == 'cat');
but also you might find working with that variable elsewhere much simpler.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Tables 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!

Translated by