I have a column vector
k =[ 0 0 0 0 0 0 2 5 6 8 7 2 1 0 0 0 0 3 5 4 1 8 6 8 ];
I want to keep the shape of the vector while replacing every 1st and 3rd non zero element with 100 so I end up with
k = [ 0 0 0 0 0 0 100 5 6 8 100 100 1 2 5 100 0 100 5 4 1 100 6 8];

댓글 수: 2

Rik
Rik 2018년 9월 19일
How are you counting? I can't reproduce your vector by any way I can think of
% 1 2 3 1 2 3 1 1 2 3 1 2 3 1
% 1 2 3 1 2 3 1 2 3 1 2 3 1 2
% (1 2 3 1 2 3)1 2 3 1 2 3 1(2 3 1 2)3 1 2 3 1 2 3
k=[ 0 0 0 0 0 0 2 5 6 8 7 2 1 0 0 0 0 3 5 4 1 8 6 8 ];
% x x x x x x x x x x
% x x x x x x x x x
% x x x x x x x x x x
None of these patterns result in your second vector. Also, there seem to be some extra values. Please explain what your pattern is, then we can try to help you find a way to implement it.
Ev
Ev 2018년 9월 19일
편집: Rik 2018년 9월 19일
% 1 2 3 1 2 3 1 1 2 3 1 2 3 1
k = [ 0 0 0 0 0 0 2 5 6 8 7 2 1 0 0 0 0 3 5 4 1 8 6 8 ];
% Counting only the non-zero elements
original vector. I want

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

 채택된 답변

Rik
Rik 2018년 9월 19일
편집: Rik 2018년 9월 19일

1 개 추천

The easiest way to do this is with a loop. A second method is less easy to follow, but removes the need for a loop. The final statement shows that the two methods are indeed interchangeable.
% 1 2 3 1 2 3 1 1 2 3 1 2 3 1
k = [ 0 0 0 0 0 0 2 5 6 8 7 2 1 0 0 0 0 3 5 4 1 8 6 8 ];
k2=k;
counter=0;
for n=1:numel(k)
if n>1 && k(n-1)==0
counter=0;%restart for next run
end
counter=counter+1;
if k(n)~=0 && ...
mod(counter,3)~=2 %"not 2" is equivalent to "1 or 3"
k2(n)=100;
end
end
run_start_inds=find([k(1)~=0 diff(k~=0)>0]);
base=ones(size(k));
base(run_start_inds)=base(run_start_inds)-mod(run_start_inds,3)+1;
countlist=cumsum(base);
countlist(k==0)=NaN;
countlist=mod(countlist,3);
k3=k;
k3(countlist==mod(1,3))=100;
k3(countlist==mod(3,3))=100;
isequal(k2,k3)

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

Ev
2018년 9월 19일

편집:

Rik
2018년 9월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by