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?
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 indicesbsxfun(@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With