How to sum previous columns before specific element ?

1 Ansicht (letzte 30 Tage)
Maria
Maria am 7 Okt. 2022
Kommentiert: Maria am 8 Okt. 2022
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 Kommentare
Torsten
Torsten am 7 Okt. 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 am 8 Okt. 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Image Analyst
Image Analyst am 8 Okt. 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

Weitere Antworten (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by