Clear Filters
Clear Filters

NEW MATRIX WITH IF CONDITIONS

1 view (last 30 days)
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]

Accepted Answer

Akira Agata
Akira Agata on 2 Mar 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

More Answers (1)

Jos (10584)
Jos (10584) on 2 Mar 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]

Categories

Find more on Loops and Conditional Statements 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!