Deleting rows of a table using for loops if consecutive terms in the first column are the same
1 次查看(过去 30 天)
显示 更早的评论
So I have a table with 33 rows and 4 columns and i want to trim the table down so that the terms in the first column are unique. The first column has a bunch of text (states in the US). I'm trying to remove rows that have the same state in the first column. Here is my code.
function output = scenarioreduction()
A = readtable("book2.xlsx")
dimensions = size(A)
nrows = dimensions(1)
ncolumns = dimensions(2)
for r = 1:nrows
if strcmp(A{r,1},A{r+1,1}) == 1
A([r+1],:) = []
r = r+1
else
end
end
end
回答(1 个)
Ruger28
2020-2-18
Please - next time use the code format. It makes this easier to look at. You're deleting an active part of the table, and changing its dimensions. Try assinging the row to remove into a variable, and adjusting it at the end.
function output = scenarioreduction()
A = readtable("book2.xlsx")
dimensions = size(A)
nrows = dimensions(1)
ncolumns = dimensions(2)
for r = 1:nrows
if strcmp(A{r,1},A{r+1,1}) == 1
% A([r+1],:) = [] this deletes a row in teh table, and changes its dimensions
removeValues(r) = r;
% r = r+1 not needed unlsess you're skipping ever other row
else
end
end
% remove the rows from the table
A(removeValues) = [];
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!