필터 지우기
필터 지우기

NEW MATRIX WITH IF CONDITIONS

조회 수: 1 (최근 30일)
PRANAY DISHAN
PRANAY DISHAN 2018년 3월 2일
댓글: PRANAY DISHAN 2018년 3월 3일
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]

채택된 답변

Akira Agata
Akira Agata 2018년 3월 2일
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
PRANAY DISHAN
PRANAY DISHAN 2018년 3월 2일
Thank you sir. It was very helpful.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jos (10584)
Jos (10584) 2018년 3월 2일
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
PRANAY DISHAN
PRANAY DISHAN 2018년 3월 3일
Thank u sir, it will shorten my program.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by