Clear Filters
Clear Filters

Access table using logical array

7 views (last 30 days)
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?

Accepted Answer

Walter Roberson
Walter Roberson on 2 Jan 2024
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

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!