NEW MATRIX WITH IF CONDITIONS

1 次查看(过去 30 天)
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 个)

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]

类别

Help CenterFile Exchange 中查找有关 Modify Image Colors 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by