Efficient way of performing operation on array after performing cumsum
1 回表示 (過去 30 日間)
古いコメントを表示
Valentina Baccetti
2022 年 3 月 22 日
コメント済み: Valentina Baccetti
2022 年 3 月 25 日
Hi,
I am fairly new to MatLab and I would like to perform the following without using a for loop. I have a matrix A to which I have applied cumsum to create another matrix B, whose row elements are the sum of the previous ones in A.
The subsequent operation I would like to perform is to divide all the elements in the same column by the index of that column. For instance, I would like to divide column 1 by 1, column 2 by 2, and column 3 by 3, and so one. In the example below, matrix B is
B = [ 1 3 6
4 9 15
7 15 24 ]
while C would be
C = [1/1 3/2 6/3
4/1 9 /2 15/3
7/1 15/2 24/3 ]
= [1.0000 1.5000 2.0000
4.0000 4.5000 5.0000
7.0000 7.5000 8.0000]
Is there any efficient way to do this without using a for loop? I thought about using arrayfun or cellfun but I have no idea of how. My initial code is below
%Example of what I want to achieve
A = [1 2 3; 4 5 6; 7 8 9];
B = cumsum(A,2);
% The operation I would like to perform
for i=1:size(B,2)
C(:,i)= B(:,i)/i;
end
0 件のコメント
採用された回答
その他の回答 (1 件)
David Goodmanson
2022 年 3 月 22 日
編集済み: David Goodmanson
2022 年 3 月 22 日
Hi Valentina,
A = [1 2 3; 4 5 6; 7 8 9];
B = cumsum(A,2);
C = (1:3).\B
This gives the result that you show in your question.
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!