0

I am trying to build a submatrix by iterating on the rows of the last column in the main matrix which is of size (50000, 21), and if the value inside is greater than 1000 then the whole corresponding y(i,:) row will be added to the new submatrix and add to it more 33 consecutive rows from the main matrix.

I wrote this code below but it is returning only a 33x21 size and I think i am iterating through the j index but not the i index:

for i=1:50000
  if y(i,21)>1000
  for j=1:33
    n(j,:)=y(j+i,:)
    j=j+1
  end
  i=i+1
end
end

What am I doing wrong?

Leb_Broth
  • 1,081
  • 1
  • 15
  • 32

2 Answers2

1

try this:

k=1;
for i=1:50000
    if y(i,21)>1000
        for j=0:33 %watch this out i am not sure how many rows you want to keep and if these involve the one with the last element greater than 1000 or not..%
            n(k,:)=y(j+i,:);
            j=j+1;
            k=k+1;
        end
    i=i+1;
    end
end

Problem is that every new set of 33 rows overwrites the previous one.The above code i think will do the trick.

CodeBlackj
  • 123
  • 8
1

this is a vectorized verison that needs no loop:

%find elements that are greater than 1000
lo = find(y(:,21) > 1000);
%indeices of 33th row after the lo,
%since it may take a value that is greater than the size of matrix we limit this value by min
up = min(size(y,1), lo + 33);
% create indices based on ranges
%see http://stackoverflow.com/a/39434045/6579744
index=cumsum(accumarray(cumsum([1;up(:)-lo(:)+1]),[lo(:);0]-[0;up(:)]-1)+1);
index= index(1:end-1);
n = y(index, :)
rahnema1
  • 15,264
  • 3
  • 15
  • 27