フィルターのクリア

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 Center および File ExchangeStructures についてさらに検索

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by