Efficient way of performing operation on array after performing cumsum

1 visualizzazione (ultimi 30 giorni)
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

Risposta accettata

Stephen23
Stephen23 il 22 Mar 2022
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

Più risposte (1)

David Goodmanson
David Goodmanson il 22 Mar 2022
Modificato: David Goodmanson il 22 Mar 2022
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.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by