Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select n elements in matrix left-wise based on certain value

I have a logical matrix A, and I would like to select all the elements to the left of each of my 1s values given a fixed distant. Let's say my distance is 4, I would like to (for instance) replace with a fixed value (saying 2) all the 4 cells at the left of each 1 in A.

A= [0 0 0 0 0 1 0
   0 1 0 0 0 0 0
   0 0 0 0 0 0 0
   0 0 0 0 1 0 1]

B= [0 2 2 2 2 1 0
   2 1 0 0 0 0 0
   0 0 0 0 0 0 0
   2 2 2 2 2 2 1]

In B is what I would like to have, considering also overwrting (last row in B), and cases where there is only 1 value at the left of my 1 and not 4 as the fixed searching distance (second row).

like image 840
umbe1987 Avatar asked Dec 06 '22 01:12

umbe1987


1 Answers

How about this lovely one-liner?

n = 3;
const = 5;
A = [0 0 0 0 0 1 0;
     0 1 0 0 0 0 0;
     0 0 0 0 0 0 0;
     0 0 0 0 1 0 1]

A(bsxfun(@ne,fliplr(filter(ones(1,1+n),1,fliplr(A),[],2)),A)) = const

results in:

A =

     0     0     5     5     5     1     0
     5     1     0     0     0     0     0
     0     0     0     0     0     0     0
     0     5     5     5     5     5     1

here some explanations:

Am = fliplr(A);                      %// mirrored input required
Bm = filter(ones(1,1+n),1,Am,[],2);  %// moving average filter for 2nd dimension
B = fliplr(Bm);                      %// back mirrored
mask = bsxfun(@ne,B,A)               %// mask for constants
A(mask) = const
like image 137
Robert Seifert Avatar answered Jan 18 '23 05:01

Robert Seifert