MATLAB: Problem with matrix manipulation- how can I avoid having to type in everything

loopsMATLABmatrices

I am looking to extract data from matrices, training (1500 by 3) and testing (500 by 3), n is the number before the colon. this is what I have by far;
% for n = 1
newTrainInput = training(1:1500,2);
newTrainOutput = training(1:1500,3);
newTestInput = testing(1:500,2);
newTestOutput = testing(1:500,3);
%for n=2
newTrainInput = [training(2:1500,2),training(1:1499,2)];
newTrainOutput = training(2:1500,3);
newTestInput = [testing(2:500,2),testing(1:499,2)];
newTestOutput = testing(2:500,3);
%for n=3
newTrainInput = [training(3:1500,2),training(2:1499,2),training(1:1498,2)];
newTrainOutput = training(3:1500,3);
newTestInput = [testing(3:500,2),testing(2:499,2),testing(1:498,2)];
newTestOutput = testing(3:500,3);
%for n=4
newTrainInput = [training(4:1500,2),training(3:1499,2),training(2:1498,2),training(1:1497,2)];
newTrainOutput = training(4:1500,3);
newTestInput = [testing(4:500,2),testing(3:499,2),testing(2:498,2),testing(1:497,2)];
newTestOutput = testing(4:500,3);
%for n=5
newTrainInput = [training(5:1500,2),training(4:1499,2),training(3:1498,2),training(2:1497,2),training(1:1496,2)];
newTrainOutput = training(5:1500,3);
newTestInput = [testing(5:500,2),testing(4:499,2),testing(3:498,2),testing(2:497,2),testing(1:496,2)];
newTestOutput = testing(5:500,3);
-
-
-
%for n=10
newTrainInput = [training(10:1500,2),training(9:1499,2),training(8:1498,2),training(7:1497,2),training(6:1496,2),training(5:1495,2),training(4:1494,2),training(3:1493,2),training(2:1492,2),training(1:1491,2)];
newTrainOutput = training(10:1500,3);
newTestInput = [testing(10:500,2),testing(9:499,2),testing(8:498,2),testing(7:497,2),testing(6:496,2),testing(5:495,2),testing(4:494,2),testing(3:493,2),testing(2:492,2),testing(1:491,2)];
newTestOutput = testing(10:500,3);

Best Answer

  • Jessie - I think tha thou can simplify the above to something like the following
    for u=1:n
    newTrainInput = [];
    newTestInput = [];
    for v=u:-1:1
    newTrainInput = [newTrainInput , training(v:1500-(u-v),2)];
    newTestInput = [newTestInput , testing(v:500-(u-v),2)];
    end
    newTrainOutput = training(u:1500,3);
    newTestOutput = testing(u:500,3);
    % do something with the arrays
    end
    In your example, n would be 10 and we would then have an inner loop where we would append data to the newTrainInput and newTestInput as per your above description. I haven't tested this, but think that it will provide a start in simplifying your code.