Matrix index is out of range for deletion and I cant figure it out

1 vue (au cours des 30 derniers jours)
Nikolas Vieira
Nikolas Vieira le 21 Fév 2020
Commenté : Nikolas Vieira le 21 Fév 2020
I am getting the error "Matrix index is out of range for deletion". What I am trying to accomplish is: where ever there is a 0 in f.....i want to delete that row number from g.
g =
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
f =
1 1 0 1 0
>> for j= 1:numel(f)
if f(j)==0
g(j,:)=[]
end
end
g =
1 1 1 1
2 2 2 2
4 4 4 4
5 5 5 5
Matrix index is out of range for deletion.
The output should be g without the 3rd and 5th row.
g=[1 1 1 1; 2 2 2 2; 4 4 4 4]

Réponse acceptée

Walter Roberson
Walter Roberson le 21 Fév 2020
Suppose you delete row 4. What was in row 5 "falls down" to row 4,what was in 6 falls to 5, and so on. If you had a request to delete row 6 then in order to delete it now, you would have to delete what is now row 5, because 6 fell to 5.
It is possible to work with a running total of the number you have deleted to figure out the current index of a given row.
However it is far easier to simply loop backwards. Delete from highest row number first: anything that falls down will be something you already know should not be deleted.
Or you could just vectorize the entire loop:
g(f==0,:) = [] ;

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing 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!

Translated by