How to add a cumulative constant to all values on each row of a matrix, starting from the bottom row and ending at the top row?

I have a matrix that is very large. A small example is:
1 2 3
1 2 3
1 2 3
I need to add a constant to each row, starting at the bottom row. The additon should be cumulative. For example, if the constant is 0.5, the matrix should become:
2.5 3.5 4.5
2.0 3.0 4.0
1.5 2.5 3.5
I know to use "cumsum" for cumulative addition in Matlab but the indexing required in this problem exceeds my skills. I would be vey grateful for any help.

 Accepted Answer

There are many ways to do this. Here is one way:
% Inputs
in = [1 2 3;
1 2 3;
1 2 3];
constant = 0.5;
% Algorithm
[m,n] = size(in);
out = in + kron(constant*(m:-1:1)',ones(1,n));

More Answers (1)

c = 0.5;
A = [1,2,3;1,2,3;1,2,3]
A = 3x3
1 2 3 1 2 3 1 2 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
One way:
N = size(A,1);
result = c*(N:-1:1).'+A
result = 3x3
2.5000 3.5000 4.5000 2.0000 3.0000 4.0000 1.5000 2.5000 3.5000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Another way:
N = size(A,1);
result = cumsum(c*ones(N,1),'reverse')+A
result = 3x3
2.5000 3.5000 4.5000 2.0000 3.0000 4.0000 1.5000 2.5000 3.5000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

5 Comments

Thank you very much indeed, Voss. I wish I could accept two answers. the cyclists worked better because my matrices are so large.
I wonder in what sense using kron is better than the approaches I showed, for large matrices.
I guess you don't use the term "better" to mean "faster", because kron seems to be the slowest.
c = 0.5;
N = 4;
T = array2table(zeros(N,4),'VariableNames',{'Size','cyclist','Voss1','Voss2'});
for n = 1:N
A = rand(10^n);
tc = timeit(@()cyclist(A,c));
tv1 = timeit(@()Voss1(A,c));
tv2 = timeit(@()Voss2(A,c));
T{n,:} = [10^n,tc,tv1,tv2];
end
T
T = 4x4 table
Size cyclist Voss1 Voss2 _____ __________ __________ __________ 10 3.5819e-05 4.8595e-06 5.0667e-06 100 2.0085e-05 1.2872e-05 7.8766e-06 1000 0.00028163 0.00019339 0.00011734 10000 0.12138 0.0996 0.096075
function B = cyclist(A,c)
[m,n] = size(A);
B = A + kron(c*(m:-1:1)',ones(1,n));
end
function B = Voss1(A,c)
B = c*(size(A,1):-1:1).'+A;
end
function B = Voss2(A,c)
B = cumsum(c*ones(size(A,1),1),'reverse')+A;
end
Thank you so much, Voss. I am currently on the road, but look forward to checking this out in more detail later. I did mean "faster" so will think about why that is an issue for me but not you. Thank you very much for thinking about this!
No problem. I was mostly just curious what you meant by "better". Thanks for clarifying you meant faster. Anyway, the time difference is not much.

Sign in to comment.

Categories

Find more on Graphics Performance in Help Center and File Exchange

Products

Release

R2024a

Asked:

on 13 Apr 2024

Commented:

on 14 Apr 2024

Community Treasure Hunt

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

Start Hunting!