필터 지우기
필터 지우기

I want to delete rows from a matrix but its giving me the error "Matrix index is out of range for deletion"

조회 수: 2 (최근 30일)
percentage_consumo= Preos2013S1(:,6)/maxconsumo;
percentage_precos= Preos2013S1(:,21)/maxpreco;
b = cellfun(@(x)str2double(x), teste1);
b2=b;
for k=2:length(teste1)
if b(k)~= 0
percentage_consumo(k,:) = [];
percentage_precos(k,:) = [];
b2(k)=[];
end
end
i=0;
for k=2:length(Preos2013S1(:,6))
if b(k)~=0
i=i+1;
end
end
All this arrays of doubles have the same size (6266x1). Besides the error that I don't understand, b2 still has a lot of rows with numbers that are not 0. And since i=2447, b2 should be 3819x1; however, its 4503x1. Can somebody please help me?

채택된 답변

Matthew
Matthew 2016년 11월 22일
편집: Matthew 2016년 11월 22일
Hi Eduardo,
One thing about deleting rows from an array while inside a for loop is that you have to account for rows that you've already deleted in previous iterations of the for loop.
For instance if you start iterating over an array with four rows, and in the first iteration you delete the first row, then when you get to the fourth iteration, there are at most three rows left. Hence if you try to delete the 'fourth' row, you are attempting to delete a non-existent row, and matlab will tell you that the "Matrix index is out of range for deletion".
A fairly easy solution to this is to iterate backwards over the array - i.e.
for k=length(teste1): -1: 2
if b(k)~= 0
percentage_consumo(k,:) = [];
percentage_precos(k,:) = [];
b2(k)=[];
end
end
This way you delete the end rows first, and you never try to access the rows where deletions are causing indexes to shift.
As for the second question - it would be helpful if you could provide more concrete examples.
  댓글 수: 1
Eduardo Rocha
Eduardo Rocha 2016년 11월 22일
Now everything is making sense, the dimensions are consistent with the expected result. Thank you very much for your help :)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Kaushik Godbole
Kaushik Godbole 2022년 4월 22일
Hello Eduardo,
The method suggested by Mathew works. However for some reason if you are required to iterate forward and still delete rows/columns in a 'for' loop and you know those rows/cloumns with reference to the original unmodified matrix, then you need to include a counter which keeps track of how many rows have been deleted. The following code illustrates how to delete only the even rows of a matrix while iterating forward. You can modify it for any 'if' condition you want.
n = 10;
A = rand(n,n);
counter = 0; %% Declaring counter to be zero
for number = 1:n
if rem(number,2) == 0
A(number - counter,:) = []; %% Takes care of changing index numbers of the rows
counter = counter + 1; %% Takes into account row deletion
end
end

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by