MATLAB: I want to save the data of the rows of U that are not empty. However, since this is inside a loop, I keep deleting the data from the previous loop. How to keep saving the data without deleting the previous one

deletefor loopisemptysavewhile loop

if isempty(U)==0
u = U(any(U,2),:);
U=[];
end
On the first iteration, it works how it should, but on the second iteration it will overwrite the previous data saved in "u". How can I fix this? It should keep saving on the next row, not deleting the previous data.

Best Answer

In most rudimentary to make work, add
u=[]; % initialize
before beginning the outer loop and then
if ~isempty(U)
u = [u; U(any(U,2),:)]; % accrete new U into u
U=[];
end
This has the issue of dynamic reallocation of u on each pass, but if isn't terribly long the runtime penalty shouldn't be too great. If it does bog down, then preallocate a very large array and populate it explicitly by keeping track of number of elements added each pass by
nU=size(U,1);
and a running total for the next insertion location into the array. And, of course, have to check don't overrun it and reallocate more room, etc., etc., if do. But, for all but the extreme cases the first solution should be just fine; wouldn't worry about the other details until after have shown that is a real performance issue on real data.
Related Question