Clear Filters
Clear Filters

How to sum previous columns before specific element ?

2 views (last 30 days)
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 Comments
Torsten
Torsten on 7 Oct 2022
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 on 8 Oct 2022
@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.

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 8 Oct 2022
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

More Answers (0)

Categories

Find more on Data Import and Export in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!