필터 지우기
필터 지우기

How to sum previous columns before specific element ?

조회 수: 2 (최근 30일)
Maria
Maria 2022년 10월 7일
댓글: Maria 2022년 10월 8일
Hello! I have a row vector E(1,50), and I have a binary matrix A (20,50). In each row of A there is only "1". I want to add values in previous columns of E before each "1" existing in A. As example E(1,6) and A(3,6)
E = [2 3 5 4 1 8 ]
A = [0 1 0 0 0 0 ;...
0 0 0 1 0 0 ;...
0 0 0 0 0 1]
I have a value k in each time I will verify if it is upper to the sum of previous element of E. For this example A(1,2) =1, so the condition is "if k- (2+3)>0, then the two columns in E."
If it is the case I will fill matrix B same dimension of A.
Now for element B(1,2)=1.
For A(2,4)=1, I will take the sum of 4 previous columns in E (4+5+3+2).
etc...
How can I do this? Thanks in advance.
  댓글 수: 4
Torsten
Torsten 2022년 10월 7일
So the aim is to create the matrix B that has the same rows as A if the condition holds and will have a zero row if not ?
And what about the value for k ? Is it constant throughout the process or does it change with the row in question ?
Maria
Maria 2022년 10월 8일
@Torsten yes "k" is constant and each time i will compare it with the sum of previous columns of E.
Thank you for your reply.

댓글을 달려면 로그인하십시오.

채택된 답변

Image Analyst
Image Analyst 2022년 10월 8일
Try this:
E = [2 3 5 4 1 8 ];
A = [0 1 0 0 0 0 ;...
0 0 0 1 0 0 ;...
0 0 0 0 0 1];
[rows, columns] = size(A);
% Initialize B
B = zeros(size(A));
for row = 1 : rows
% Find the first column where A is 1 for this row.
first1column = find(A(row, :), 1, 'first');
% Sum the values of E from column 1 up until this first1column and
% assign to B in that row and column
B(row, first1column) = sum(E(1:first1column));
end
% Display B in command window
B
B = 3×6
0 5 0 0 0 0 0 0 0 14 0 0 0 0 0 0 0 23

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by