StatsCode
StatsCode

Reputation: 39

Count rows containing zeros between consecutive numbers in matlab

I would like to rename zeros between consecutive numbers in rows of a column. For example, I need output A to look like output Anew.

A = [1, 0, 0, 0, 2, 0, 3, 0, 0, 0, 0, 0, 4]

A =

 1     0     0     0     2     0     3     0     0     0     0     0     4

Anew = [1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 4]

Anew =

 1     1     1     1     2     2     3     3     3     3     3     3     4

Any help would be very much appreciated and thanks in advance :)

Upvotes: 0

Views: 44

Answers (2)

rahnema1
rahnema1

Reputation: 15837

If they are consecutive positive numbers you can use cummax:

Anew = cummax(A) ;

Upvotes: 2

Sardar Usama
Sardar Usama

Reputation: 19689

Replace zeros with NaNs and then use fillmissing to replace NaNs with the previous non-NaN value.

Anew = A;
Anew(Anew==0) = NaN; 
Anew = fillmissing(Anew,'previous');

or as a one-liner using standardizeMissing with fillmissing:

Anew = fillmissing(standardizeMissing(A,0),'previous');

Upvotes: 3

Related Questions