Efficient way of performing operation on array after performing cumsum

1 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2022-3-22
A = [1,2,3;4,5,6;7,8,9];
B = cumsum(A,2);
C = B./(1:3)
C = 3×3
1.0000 1.5000 2.0000 4.0000 4.5000 5.0000 7.0000 7.5000 8.0000

更多回答(1 个)

David Goodmanson
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 CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by