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?

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

采纳的回答

the cyclist
the cyclist 2024-4-13,17:36
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));

更多回答(1 个)

Voss
Voss 2024-4-13,17:32
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 个评论
Srh Fwl
Srh Fwl 2024-4-14,18:45
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!
Voss
Voss 2024-4-14,18:53
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by