I have a 3D matrix called mat
. Every column may or may not comprise a variable number of leading zeros. I need to replace them with NaNs. It's important to recognize that there might follow even more zeros in any column after the occurence of the first non-zero elements. That is, just indexing ALL zeros in the matrix and replacing them with NaN won't lead to the correct result.
I do have a working solution. However, it contains two for-loops. I am wondering whether it's possible to vectorize and get rid of the loop. In reality, mat
could be very big, something like 10000x15x10000. Therefore, I am quite sensitive to execution speed.
Here's my toy example:
% Create test matrix
mat = randi(100,20,5,2);
mat(1:5,1,1) = 0;
mat(1:7,2,1) = 0;
mat(1:3,4,1) = 0;
mat(1:10,5,1) = 0;
mat(1:2,1,2) = 0;
mat(1:3,3,2) = 0;
mat(1:7,4,2) = 0;
mat(1:4,5,2) = 0;
% Find first non-zero element in every column
[~, firstNonZero] = max( mat ~= 0 );
% Replace leading zeros with NaN
% How to vectorize this part???
[nRows, nCols, nPlanes] = size(mat);
for j = 1 : nPlanes
for i = 1 : nCols
mat(1:firstNonZero(1, i, j)-1, i, j) = NaN;
end
end