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

2 Ansichten (letzte 30 Tage)
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

Antworten (1)

Ruger28
Ruger28 am 18 Feb. 2020
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

Kategorien

Mehr zu Environment and Settings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by