Hot to store results from for loop in matrix
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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;
2 Kommentare
EmielH
am 7 Feb. 2020
I think the probleming you're having is caused by the fact that you're overwriting deltaEI deltaEA and deltaP in your if statement. Furthermore I think you can skip the if statement if you let m run from 2:9. Not sure what your code should do or wat CI etc are but I think it should look something 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
resultsco2=deltaCI.*deltaEI.*deltaEA.*deltaP;
Akzeptierte Antwort
KSSV
am 7 Feb. 2020
Bearbeitet: KSSV
am 7 Feb. 2020
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
2 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!