Borrar filtros
Borrar filtros

NEW MATRIX WITH IF CONDITIONS

1 visualización (últimos 30 días)
PRANAY DISHAN
PRANAY DISHAN el 2 de Mzo. de 2018
Comentada: PRANAY DISHAN el 3 de Mzo. de 2018
Hello everyone
I have the following 2 matrices in which S1 is randomly developed.I need to develop another matrix D2 in which if S1(i)=1 and while S1(i) stays 0 for the next positions, D2(i) should be added until S1(i)=1 again as shown.
Please help me on this
D1=[10 20 30 40]
S1=[1 0 0 1]
D2=[60 0 0 40]

Respuesta aceptada

Akira Agata
Akira Agata el 2 de Mzo. de 2018
Like this?
D1 = [10 20 30 40];
S1 = [1 0 0 1];
D2 = zeros(size(D1));
pt = find(S1);
for kk = 1:numel(pt)
if kk < numel(pt)
D2(pt(kk)) = sum(D1(pt(kk):pt(kk+1)-1));
else
D2(pt(kk)) = sum(D1(pt(kk):end));
end
end
  1 comentario
PRANAY DISHAN
PRANAY DISHAN el 2 de Mzo. de 2018
Thank you sir. It was very helpful.

Iniciar sesión para comentar.

Más respuestas (1)

Jos (10584)
Jos (10584) el 2 de Mzo. de 2018
No need for loops or ifs:
% data
D1 = [ 10 20 30 40 50 60]
S1 = [ 1 0 0 1 1 0]
% engine
D2 = zeros(size(D1))
D2(S1==1) = accumarray(cumsum(S1(:)), D1)
% D2 = [60 0 0 40 110 0]
  1 comentario
PRANAY DISHAN
PRANAY DISHAN el 3 de Mzo. de 2018
Thank u sir, it will shorten my program.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements 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