필터 지우기
필터 지우기

Replace jth zero in vector with j

조회 수: 1 (최근 30일)
Scott
Scott 2014년 9월 27일
답변: Mohammad Abouali 2014년 9월 27일
I would like to take a vector x as an input and (assuming that it has 0s), replace each 0 with the index of zero that it is. For example: >> x = [1 0 2 4 -3 0 3 0]; Would turn into: >>x_new = [1 1 2 4 -3 2 3 3]; Here is my code so far:
z = length(find(x==0)); count = 1;
for i=1:z
x(find(x==0))=count;
count = count + 1;
end;
This code just replaces all of the 0 elements with a 2. I want it to go through and count the zeroes off, and I am not sure at all where I am going wrong...
Any Thoughts?
Thanks!

채택된 답변

Mohammad Abouali
Mohammad Abouali 2014년 9월 27일
zeroMask = (x==0);
x(zeroMask) = 1:sum(zeroMask);

추가 답변 (1개)

Youssef  Khmou
Youssef Khmou 2014년 9월 27일
try :
x = [1 0 2 4 -3 0 3 0];
y=x;
[a,b]=find(x==0);
y(b)=b;
  댓글 수: 2
Scott
Scott 2014년 9월 27일
That code gives me a new vector y that has all of the zeroes replaced by the index of that zero in the vector. i.e:
>>x=[1 0 2 4 -3 0 3 0]; >>y=[1 2 2 4 -3 6 3 8]
which is close, but not quite what i am looking for
Geoff Hayes
Geoff Hayes 2014년 9월 27일
Rather than assigning b as the result, just do the following
y(b) = 1:length(b);
as 1:length(b) will produce a vector with the same length as b with values in the order of 1,2,3,..

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by