Borrar filtros
Borrar filtros

How to sum previous columns before specific element ?

2 visualizaciones (últimos 30 días)
Maria
Maria el 7 de Oct. de 2022
Comentada: Maria el 8 de Oct. de 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 comentarios
Torsten
Torsten el 7 de Oct. de 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 el 8 de Oct. de 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.

Iniciar sesión para comentar.

Respuesta aceptada

Image Analyst
Image Analyst el 8 de Oct. de 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

Más respuestas (0)

Categorías

Más información sobre Data Import and Export en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by