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

5 ビュー (過去 30 日間)
ak
ak 2020 年 2 月 18 日
回答済み: Ruger28 2020 年 2 月 18 日
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 Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by