I have a question above removing rows from a matrix. I have the code below which removes the rows I want, but the problem is each time a row is removed it changes the size of the matrix. When the size of the matrix changes, the for loops can no longer run through the original size of the matrix because it has changed. Does anyone know how to get around this? Thanks.
for i = 1:NT
for j = 1:NP
for k = 1:NP
if ContactPartData((i-1)*(NP*(NP-1)) ((j-1)*NP k),2) == 0
ContactPartData((i-1)*(NP*(NP-1)) ((j-1)*NP k),:) = [];
else
end
end
end
end
CodePudding user response:
For these cases, it is typically easier to record which rows you want to remove, and then remove them all at once at the end. This is more efficient than repeatedly removing a single row. And it solves your problem at the same time!
toremove = false(size(ContactPartData,1),1);
for i = 1:NT
for j = 1:NP
for k = 1:NP
if ContactPartData((i-1)*(NP*(NP-1)) ((j-1)*NP k),2) == 0
toremove((i-1)*(NP*(NP-1)) ((j-1)*NP k)) = true;
end
end
end
end
ContactPartData(toremove,:) = [];
Of course, in this particular case, the loop is not needed at all:
toremove = ContactPartData(:,2) == 0;
ContactPartData(toremove,:) = [];
Additionally, it might be more efficient to do it the other way around, selecting which rows to preserve (time the code to find out!):
tokeep = ContactPartData(:,2) ~= 0;
ContactPartData = ContactPartData(tokeep,:);