Hot to store results from for loop in matrix

1 回表示 (過去 30 日間)
Sandra Levin
Sandra Levin 2020 年 2 月 7 日
コメント済み: KSSV 2020 年 2 月 7 日
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 件のコメント
EmielH
EmielH 2020 年 2 月 7 日
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;
Sandra Levin
Sandra Levin 2020 年 2 月 7 日
Thank you! your suggestion did the trick!

サインインしてコメントする。

採用された回答

KSSV
KSSV 2020 年 2 月 7 日
編集済み: KSSV 2020 年 2 月 7 日
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 件のコメント
Sandra Levin
Sandra Levin 2020 年 2 月 7 日
Thank you! This works perfectly!
KSSV
KSSV 2020 年 2 月 7 日
thnaks is accepting the answer.....?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by