필터 지우기
필터 지우기

Access table using logical array

조회 수: 7 (최근 30일)
TrickyHeron
TrickyHeron 2024년 1월 2일
댓글: TrickyHeron 2024년 1월 2일
Is there a better way to index a table using a logical array?
Code to reproduce my issue:
Acol = [1; 2; 3; 4; 5; 6];
Bcol = [1; 2; 3; 4; 5; 6];
Ccol = [1; 2; 3; 4; 5; 6];
dataArray = [Acol Bcol Ccol];
mask1 = dataArray == 5;
dataArray(mask1) = nan; % do something to all 5s in the table
dataTable = table(Acol,Bcol,Ccol);
mask = dataTable == 5;
mask = table2array(mask);
dataTable(mask) = nan % error
The error is "Error using () Subscripting into a table using one subscript (as in t(i)) is not supported. Specify a row subscript and a variable subscript, as in t(rows,vars). To select variables, use t(:,i) or for one variable t.(i). To select rows, use t(i,:)."
Reading the documentation for table data access indicates that logical indexing is possible if I have a mask vector and use it for either the rows or columns of dataTable. For instance I get no errors doing the following:
mask = dataTable.Acol == 5;
dataTable(mask,:) % returns the row corresponding to the mask
However, I would like to logically index a table as I would for an array. I can do this if I first convert the table to an array, logically index, and then convert the array back to a table:
namesCell = dataTable.Properties.VariableNames;
dataTable = table2array(dataTable)
mask = dataTable == 5;
dataTable(mask) = nan;
dataTable = array2table(dataTable,'VariableNames',namesCell);
Is there a more efficient/ergonomic way to do this?

채택된 답변

Walter Roberson
Walter Roberson 2024년 1월 2일
Acol = [1; 2; 3; 4; 5; 6];
Bcol = [1; 2; 3; 4; 5; 6];
Ccol = [1; 2; 3; 4; 5; 6];
dataTable = table(Acol,Bcol,Ccol);
dataTable = standardizeMissing(dataTable, 5)
dataTable = 6×3 table
Acol Bcol Ccol ____ ____ ____ 1 1 1 2 2 2 3 3 3 4 4 4 NaN NaN NaN 6 6 6
  댓글 수: 1
TrickyHeron
TrickyHeron 2024년 1월 2일
Thank you this worked wonderfully.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by