Deleting rows of a table using for loops if consecutive terms in the first column are the same

조회 수: 2 (최근 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
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

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by