1
votes

I don't see the bug anymore...maybe (very probably :-) ) there's even a much more easier and faster way of doing it... I summarized the important columns of my huge data frame in a little expData (see below).

The problem is actually quite easy, but I'm just blind for the easy idea of solving it..

My objective is to reshape columns b,c,d into one column that expData afterwards looks like expData2.

I would be really happy, if someone could help me out.

My code so far:

  a = [1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5]';
  b = [0.3 0.3 0.3 0.3 0.3 0.4 0.4 0.4 0.4 0.4 0.5 0.5 0.5 0.5 0.5 0.8  0.8 0.8 0.8 0.8 0.9 0.9 0.9 0.9 0.9]';
  c = [0.4 0.4 0.4 0.4 0.4 0.6 0.6 0.6 0.6 0.6 0.8 0.8 0.8 0.8 0.8 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1]';
  d = [0.5 0.5 0.5 0.5 0.5 0.1 0.1 0.1 0.1 0.1 0.7 0.7 0.7 0.7 0.7 0.2 0.2 0.2 0.2 0.2 0.3 0.3 0.3 0.3 0.3]';
  e = rand(25,1);
  f = rand(25,1);

  a2 = [2 3 4 2 3 4 2 3 4 2 3 4 2 3 4]';
  b2 = [0.3 0.4 0.5 0.4 0.6 0.1 0.5 0.8 0.7 0.8 0.9 0.2 0.9 0.1 0.3]';
  c2 = rand(15,1);
  d2 = rand(15,1);
  expData = horzcat(a,b,c,d,e,f); 
  expData2 = horzcat(a2,b2,c2,d2); % for explanation of my objective

  k = horzcat(expData(:,2),expData(:,3),expData(:,4))'; % How I wanted to do it
  expData(:,2:4) = [];
  k = reshape(k,[],1);
  for index = 1:size(expData,1)
        if expData(index,1) == 1
          expData(index,:) = [];
        end
        if expData(index,1) == 5
          expData(index,:) = [];
        end
   end
   k = k(1:size(expData,1),:);
   expData2 = [expData k];
1

1 Answers

0
votes

Your current code throws an error, since the number of loop iterations gets determined at the beginning of the loop. As you are removing rows of expData, you run out of rows to index at some point.

The quick fix would be to start looping from the back, i.e. use for index = size(expData,1):-1:1. This way, you can safely remove rows without running into indexing problems.

The elegant fix is to use ismember to identify rows to remove:

rows2remove = ismember(expData(:,1),[1 5]);
expDate(rows2remove,:) = [];