Filter löschen
Filter löschen

Access table using logical array

7 Ansichten (letzte 30 Tage)
TrickyHeron
TrickyHeron am 2 Jan. 2024
Kommentiert: TrickyHeron am 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?

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 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

Weitere Antworten (0)

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Produkte


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by