within context of writing function, have following example matrix:
temp = 1 2 0 0 1 0 1 0 0 0 0 0 0 1 0 0 0 1
i want obtain array each element indicates number of element out of non-zero elements starts column. if column empty, element should correspond next non-empty column. matrix temp
, result be:
result = [1 3 5 5 5 6]
because first non-zero element starts first column, third starts second column, fifth starts fifth column , sixth starts sixth column.
how can operation general matrix (one may or may not contain empty columns) in vectorized way?
code:
temp = [1 2 0 0 1 0; 1 0 0 0 0 0; 0 1 0 0 0 1] t10 = temp~=0 l2 = cumsum(t10(end:-1:1)) temp2 = reshape(l2(end)-l2(end:-1:1)+1, size(temp)) result = temp2(1,:)
output:
temp = 1 2 0 0 1 0 1 0 0 0 0 0 0 1 0 0 0 1 t10 = 1 1 0 0 1 0 1 0 0 0 0 0 0 1 0 0 0 1 l2 = 1 1 1 1 1 2 2 2 2 2 2 2 3 3 4 4 5 6 temp2 = 1 3 5 5 5 6 2 4 5 5 6 6 3 4 5 5 6 6 result = 1 3 5 5 5 6
printing values of each step may clearer explanation. use cumsum
ids of non-zero elements. need know id before reaching element, reversed cumsum
do. thing left reverse id numbers back.
Comments
Post a Comment