필터 지우기
필터 지우기

Directly perform a multiplication on certain variables in a table

조회 수: 30 (최근 30일)
James Browne
James Browne 2021년 11월 25일
댓글: Peter Perkins 2021년 11월 26일
Hi,
I have a table such as
x y z
a 1 2
b 3 4
a 5 6
I want to multiply rows where the first column = b by 1000 but not touch the other rows.
I know I can get the values using a logical operatior
table.x == "b"
but I wasn't sure if I can use this logical operation to multiply the rows in place on the table without touching the other rows, without doing a for loop. My table has a lot of data so a for loop through each row is quite slow. Hence I am looking for a faster way than:
for i = 1:3
if table.x(i) == "b"
table.y(i)=table.y(i)*1000;
table.z(i)=table.z(i)*1000;
else
% do nothing
end
end

채택된 답변

Stephen23
Stephen23 2021년 11월 25일
편집: Stephen23 2021년 11월 25일
T = cell2table({'a',1,2;'b',3,4;'a',5,6},'VariableNames',{'x','y','z'})
T = 3×3 table
x y z _____ _ _ {'a'} 1 2 {'b'} 3 4 {'a'} 5 6
idx = strcmp(T.x,'b');
T{idx,{'y','z'}} = T{idx,{'y','z'}}*1000
T = 3×3 table
x y z _____ ____ ____ {'a'} 1 2 {'b'} 3000 4000 {'a'} 5 6
Or alternatively:
T.y(idx) = T.y(idx)*1000;
T.z(idx) = T.z(idx)*1000;
  댓글 수: 1
Peter Perkins
Peter Perkins 2021년 11월 26일
Even better if you can use the string type rather than a cell array of char vectors, because then
idx = strcmp(T.x,'b');
becomes the more readable
T.x == "b"

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by