An accumulating matrix to be reset when the limit value is reached, the value being reset must be moved to another matrix

조회 수: 4 (최근 30일)
Hello
can someone please help me with this challenge.
matrix
B = [1, 4, 3, 1, 3, 2, 1, 0, 0, 1, 5, 6, 9, 1, 3]
A = cumsum (B);
A = [1, 5, 8, 9, 12, 14, 15, 15, 15, 16, 21, 27, 36, 37, 40]
Then i want A and C to act like this
A = [1, 0, 3, 4, 0, 2, 3, 3, 3, 4, 0, 0, 0, 1, 3] % Every time it exceds 5, the value has to be moved to C, and reset to 0
C = [0, 5, 0, 0, 7, 0, 0, 0, 0, 0, 9, 6, 9, 0, 0]
  댓글 수: 3
Rune Kalhoej
Rune Kalhoej 2019년 5월 12일
primary loops, like this
clc
B = [5,3,4,7,8,6,3,2,1,0,3,2,7,8,3,4,2];
A = cumsum(B); %Dette er den matrice du vil sortere alt over 5
C = zeros(length(A),1); %Alle værdier over 5 fra Matrix matricen, bliver lagt over i denne, resten er 0.
for i = 1:length(A)
if A(i)>=5
C(i) = A(i);
A(i) = 0; % den skal samtidig nulstilles , virker ikke :S
else
C(i) = 0;
end
end
table(A',C)

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

채택된 답변

Rik
Rik 2019년 5월 12일
This should do the trick. Note that you should use numel to count the number of elements, not length, which is just doing max(size(A)). The difference is usually nothing, but it will trip you up at some point.
B = [1, 4, 3, 1, 3, 2, 1, 0, 0, 1, 5, 6, 9, 1, 3];
A = cumsum (B);
C = zeros(size(A));
idx=find(A>=5);
while ~isempty(idx)
idx=idx(1);
C(idx)=A(idx);
A(idx:end)=A(idx:end)-A(idx);
idx=find(A>=5);
end
FormatSpec=[repmat('%d, ',1,numel(A)) '\n'];FormatSpec(end-3)='';
clc
fprintf(FormatSpec,A)
fprintf(FormatSpec,C)
Alternatively (which might be faster in some cases):
B = [1, 4, 3, 1, 3, 2, 1, 0, 0, 1, 5, 6, 9, 1, 3];
A = cumsum (B);
C = zeros(size(A));
idx=find(A>=5);
while ~isempty(idx)
idx=idx(1);
C(idx)=A(idx);
A=A-A(idx);
idx=find(A>=5);
end
A=cumsum(B)-cumsum(C);%restore real A

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by