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?
조회 수: 2 (최근 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.
댓글 수: 0
채택된 답변
the cyclist
2024년 4월 13일
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));
댓글 수: 0
추가 답변 (1개)
Voss
2024년 4월 13일
c = 0.5;
A = [1,2,3;1,2,3;1,2,3]
One way:
N = size(A,1);
result = c*(N:-1:1).'+A
Another way:
N = size(A,1);
result = cumsum(c*ones(N,1),'reverse')+A
댓글 수: 5
Voss
2024년 4월 14일
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 Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!