Access table using logical array
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
TrickyHeron
le 2 Jan 2024
Commenté : TrickyHeron
le 2 Jan 2024
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?
0 commentaires
Réponse acceptée
Walter Roberson
le 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)
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Structures dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!