1
votes

I have a big matrix of numerical data, let assume here for practicity a small matrix

a=[1 1 1;
   1 1 1]

Then I have a vector of indices

b=[4;
   2]

My goal is to "apply" vector b to a, row by row, in such a way to nullify all the items of the i-th row of a which are falling in the columns whose indices are greater than the i-th element of b, when possible.

Therefore my desired output would be:

c=some_smart_indexing_operation(a,b) %this is pseudo-code of course
c=[1 1 1;
   1 0 0]

Let me comment the results row by row:

  • on the first row, b's first element is 4: having a only 3 colums no element is nullify

  • on the second tow, b's second element is 2: I should nullify the second and the third element of this row.

I could perform such an operation with a for loop by I was wondering if I could get the same result applying some smart indexing operation or applying some vectorial native functions.

1

1 Answers

2
votes

You can use bsxfun to create a mask of zero-one values, and then multiply a element-wise by that mask:

c = a .* bsxfun(@lt, 1:size(a,2), b);

In Matlab R2016b onwards the following simpler syntax can be used:

c = a .* ((1:size(a,2))<b);

Another approach is to use the complementary mask to the one above as a logical index to write the zeros.

c = a;
c(bsxfun(@ge, 1:size(a,2), b)) = 0; % or c(((1:size(a,2))>=b)) = 0