How to sum previous columns before specific element ?

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