How do I change a specific row of a table that I manually filtered out?
4 views (last 30 days)
Show older comments
MathWorks Support Team
on 23 Mar 2023
Edited: MathWorks Support Team
on 16 Apr 2024 at 19:43
I have a table of > 1 million rows. I need to find a specific row in this table and update 2 columns. I can find the row by filtering by 3 columns:
filter = (Table.A == "a" & Table.B == "b" & Table.C == "c");
row = Table(filter, : );
Here, “row” is the correctly filtered. I then assign new values to the row's elements by using the following commands:
row.D = “d”;
row.E = “e”
One would assume that the 'D' and 'E' elements of the row are now updated , but when I print out the table, they still show the old values.
I was able to successfully edit the table by iterating through the > 1 million rows, and calling the list of updates (50,000 lines long). But this procedure takes hours. How can I efficiently achieve this workflow?
Accepted Answer
MathWorks Support Team
on 15 Apr 2024 at 0:00
Edited: MathWorks Support Team
on 16 Apr 2024 at 19:43
The issue here is that "row" is not a pointer to the row in the table. It is a copy of the value there. After updating "row" to the desired values, you need to directly set the table's row by doing something like this:
table(filter, :) = row;
Here's a complete example of filtering the rows and setting the table correctly:
%% Generate a table
A = ["a" "a" "b" "x" "a" "a"]'; B = ["g" "b" "b" "f" "x" "b"]'; C = ["c" "c" "f" "c" "c" "e"]';
D = repmat(string, 1, 6)'; E = repmat(string, 1, 6)';
T = table(A, B, C, D, E);
%% Filter and replace the data
filter = (T.A == "a" & T.B == "b" & T.C == "c");
row = T(filter, :);
row.D = "d";
row.E = "e";
T(filter, :) = row; % Try commenting and uncommenting this line to see the difference in T
0 Comments
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!