MATLAB: Hot to store results from for loop in matrix

for loopstoring output in matrix

So,
I'm having trouble storing my results from a for loop in a matrix. I have a 22*9 matrix for which I want to calculate the diffferennce between the columns, for each row. and store it in a new matrix.
I have tried preallocating with zeroes, does not fix the probelm. Something is wring in my code (see below) but I can't seem to figure out what.
What happens is that the output is either (with preallocation) a 22*9 Matrix with only the output of the last calculation in the first and second column of the matrix.
Or, withour preallocation, I get the result as 9 separate vectors, one for each iteration.
very grateful for some input.
Thx!
The code:
for m=1:9
if m==1
deltaCI=0;
deltaEA=0;
deltaP=0;
else
%calculate difference for CI, EI, EA, between year (column) m and m-1 for each of the 22 rows.
deltaCI=CI(:, m)- CI(:, m-1);
deltaEI=EI(:, m)- EI(:, m-1);
deltaEA=EA(:, m)- EA(:, m-1);
deltaP=P(:, m)- P(:, m-1);
end'
deltaCI(:,m)=deltaCI
deltaEI(:,m)=deltaEI
deltaEA(:,m)=deltaEA
end
resultsco2(:,m)=deltaCI.*deltaEI.*deltaEA.*deltaP;

Best Answer

You need not to run a loop to get the difference..simply use the fucntion diff.
A = rand(22,9) ;
A = [zeros(22,1) A] ;
iwant = diff(A')' ;
Still, if you want o use the loop. Use like this:
deltaCI = zeros(22,9) ;
deltaEA = zeros(22,9) ;
deltaP = zeros(22,9) ;
for m=2:9
%calculate difference for CI, EI, EA, between year (column) m and m-1 for each of the 22 rows.
deltaCI(:,m)=CI(:, m)- CI(:, m-1);
deltaEI(:,m)=EI(:, m)- EI(:, m-1);
deltaEA(:,m)=EA(:, m)- EA(:, m-1);
deltaP(:,m)=P(:, m)- P(:, m-1);
end