I have got a matrix in a loop which is
m=
-132.5901 -137.2695 -114.1264 -131.4986 -134.5733 Inf
Inf Inf Inf -135.2631 -121.7322 -119.7471
-132.7978 -123.8068 -135.9385 Inf -134.1602 -117.6997
-130.1930 -134.0093 -137.4125 -128.7641 Inf -116.0473
I want a command which can be used in loop to get the answer as:
-132.5901 -137.2695 -114.1264 -131.4986 -134.5733 -119.7471
-132.7978 -123.8068 -135.9385 -135.2631 -121.7322 -117.6997
-130.1930 -134.0093 -137.4125 -128.7641 -134.1602 -116.0473
I don't want a single vector using isfinite command. The matrix size should be retained automatically using Matlab.
I'm going to assume that in retaining the size of the original matrix, you want us to pad the bottom of the solution matrix with NaN. I'm also going to assume that there might be more than one Inf in any given column. In that case the following loop-based solution works for me:
%# Set up an example matrix
M = [Inf 2 Inf 4; 5 Inf 6 7; Inf Inf 8 Inf];
[T, N] = size(M);
%# Get an index of finite elements
I1 = isfinite(M);
%# Solution 1
Soln1 = NaN(T, N);
for n = 1:N
CurCol = M(:, n);
Soln1(1:sum(I1(:, n)), n) = CurCol(I1(:, n));
end
There is probably a fully-vectorized solution to this problem for the general case (there definitely is - see my update below). However, I'd be surprised if it yields much of a speed-up over the loop-based solution. Single loops are now very fast in Matlab IF you set your problem up so you can operate on the columns of a matrix (as opposed to the rows), since these elements are allocated sequentially in memory.
Now, let us assume that there is only one Inf per column. In this case, the problem is much easier to solve, and can be done with the following one-liner:
%# Solution 2
Soln2 = [reshape(M(isfinite(M)), T-1, N); NaN(1, N)];
Solution 2 will obviously fail for the example matrix I set up, since 6 elements can not be re-arranged into a T-1 by N (ie 2 by 4) matrix.
UPDATE: Okay, so for no good reason, it was annoying me that I couldn't do it without a loop. Thus, here is a loop-less solution:
%# Solution 3
Soln3 = NaN(T, N);
I2 = bsxfun(@plus, cumsum(isfinite(M)), (0:T:T*(N-1)));
I2 = I2(:);
I2(I1 == 0) = [];
Soln3(I2) = M(isfinite(M));
Quick (very) non-rigorous speed test on loop versus non-loop solution:
Elapsed time is 0.203997 seconds.
Elapsed time is 0.251969 seconds.
The non-loop solution will probably improve (relatively speaking) though if M is bigger.
Now I need to get back to work :-)
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