How to modify table elements without using a for loop?

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

 채택된 답변

Stephen23
Stephen23 2018년 11월 4일
편집: Stephen23 2018년 11월 4일
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

Perfect, thanks.
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Tables에 대해 자세히 알아보기

질문:

2018년 11월 4일

댓글:

2018년 11월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by