Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace non-NaN values with their row indices within matrix

Tags:

matrix

matlab

I have the 4x2 matrix A:

A = [2 NaN 5 8; 14 NaN 23 NaN]';

I want to replace the non-NaN values with their associated indices within each column in A. The output looks like this:

out = [1 NaN 3 4; 1 NaN 3 NaN]'; 

I know how to do it for each column manually, but I would like an automatic solution, as I have much larger matrices to handle. Anyone has any idea?

like image 225
Bowecho Avatar asked Oct 03 '16 11:10

Bowecho


1 Answers

out = bsxfun(@times, A-A+1, (1:size(A,1)).');

How it works:

  • A-A+1 replaces actual numbers in A by 1, and keeps NaN as NaN
  • (1:size(A,1)).' is a column vector of row indices
  • bsxfun(@times, ...) multiplies both of the above with singleton expansion.

As pointed out by @thewaywewalk, in Matlab R2016 onwards bsxfun(@times...) can be replaced by .*, as singleton expansion is enabled by default:

out = (A-A+1) .* (1:size(A,1)).';

An alternative suggested by @Dev-Il is

out = bsxfun(@plus, A*0, (1:size(A,1)).');

This works because multiplying by 0 replaces actual numbers by 0, and keeps NaN as is.

like image 85
Luis Mendo Avatar answered Sep 29 '22 10:09

Luis Mendo