Inverting and reshaping matrix which includes NaNs
15 views (last 30 days)
Show older comments
I have a 3056 x 29 matrix where the rows represent time and columns represent current speed at various heights above the seabed - giving a current speed profile (where column 1 is closest the seabed and 29 furthest away). As there is a tide, which affects the height of water above the seabed over time, I have replaced all values above a certain height (the sea surface) with NaN (as shown below). I would now like to effectively invert the current speed profile for each row (i.e. time step) so that the columns represent water current speed at various depths below the sea surface. I have tried a variety of inverting and reshaping functions but, as the matrix contains NaNs, when these are removed the matrix is irregularly sized - which Matlab cannot work with.
Any suggestions would be appreciated! Many thanks
Jamie
0 Comments
Accepted Answer
Thorsten
on 21 Oct 2015
Edited: Thorsten
on 21 Oct 2015
You can rearrange the matrix by reversing the order of the non-NaN elements in each row such that the first column represents the velocity closest to the surface:
A = [1 2 3 4 NaN NaN; 1 2 3 NaN NaN NaN; 1 2 NaN NaN NaN NaN]; % small sample matrix to test
idx = sum(isnan(A),2);
B = A;
for i=1:size(A,1)
B(i,1:end-idx(i)) = A(i,end-idx(i):-1:1);
end
2 Comments
Thorsten
on 21 Oct 2015
Edited: Thorsten
on 21 Oct 2015
It is hopefully not too hard to understand. The idx = sum(isnan(A),2) line determines the number of NaNs in a row. Because they all appear in the end, the non-NaNs are at positions 1:end-idx(i). You reverse the order of these numbers if you count down from end-idx(i) to 1, i.e., end-idx(i):-1:1. So the code flips all numbers in a row from left to right.
More Answers (0)
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!