Deleting rows of a table using for loops if consecutive terms in the first column are the same
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
Réponses (1)
Ruger28
le 18 Fév 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
0 commentaires
Voir également
Catégories
En savoir plus sur Environment and Settings dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!