# MATLAB: Dynamically adding element to an array

array operations

Dear Community,
Still new to matlab and exploring, It may be a simple problem but I am stuck for sometime on trying to come out with a clean logic .
Say i have an array (N X 2 )
signal price
1 29.21
-1 29.41
-1 29.43
-1 29.63
1 29.01
0 29.21
1 28.62
1 28.82
I wanted to add a row if the consecutive row in column 1 is -1 to 1 or -1 to 1 , the row to be added is a 0 and column 2 will be the price in the next row.
Basically a 1 is a long signal and -1 is a short signal and 0 is exit a position (in finance). The problem with the original data is when the scenario is from long to short ( 1 to -1) , i need to exit it before shorting , so i need to add a row with 0 and the price to exit.
The result I am expecting will be :
signal price
1 29.21
-1 29.41
-1 29.43
-1 29.63
1 29.01
0 29.21
1 28.62
1 28.82
The code I attempted :
spread = y;   %pricetemp=NaN(length(spread), 2); % initialise N X 2 arraytemp(:,2)=spread; % put price into 2nd column%numUnits is a single row of signals (eg : -1,0,1...)for i = 2:numel(numUnits)            temp(i,1)=numUnits(i);           compare = abs(numUnits(i)-numUnits(i-1));          if  compare == 2                temp = [temp(1:i-1,:); temp(i:i,:); temp(i:end,:)];          temp(i,1)=0;                %temp(i,2)=i;      endend
The result is incorrect because the for loop is always operating on the original NumUnits array and not the Temp where I am adding the extra rows. I dont have an elegant solution to add dynamically an array and operate it on the fly.
Anyone able to help or give some clue? Thanks in advance!
Darren

priceArray= ...    [1   29.21    -1  29.41    -1  29.43    -1  29.63    1   29.01    0   29.21    1   28.62     1   28.82]y=priceArray(:, 2);numUnits = priceArray(:, 1);% YOUR CODE WITH MODIFICATIONS:spread = y;   %pricetemp=NaN(2*length(spread), 2); % initialise N X 2 array TWICE the size of the origin%temp(:,2)=spread; % put price into 2nd column%numUnits is a single row of signals (eg : -1,0,1...)idx = 1;  % introduce second index variablefor i = 2:numel(numUnits)            %temp(i,1)=numUnits(i);           compare = abs(numUnits(i)-numUnits(i-1))          if  compare == 2          temp(idx, :) = priceArray(i-1, :);          idx = idx + 1;          temp(idx, :) = [0 priceArray(i, 2)];                          else          temp(idx, :) = priceArray(i-1, :);      end      idx = idx + 1;endtemp(idx, :) = priceArray(i, :); % add last row which always equals the origintemp = temp(1:idx, :)