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