Squeezing NaN's out of a square matrix to make a smaller square matrix

2 views (last 30 days)
I have a matrix that looks like this:
M =[NaN 1 1 1 1
2 NaN 2 2 2
3 3 NaN 3 3
4 4 4 NaN 4
5 5 5 5 NaN];
and I want to remove the NaN's and retain the matrix shape so that it looks like this:
M =[2 1 1 1 1
3 3 2 2 2
4 4 4 3 3
5 5 5 5 4];
I can't figure out how to code that though. Any suggestions?

Accepted Answer

Wan Ji
Wan Ji on 27 Aug 2021
[p,q] = size(M);
M(isnan(M))=[];
M = reshape(M,p-1,q)
Then
M =
2 1 1 1 1
3 3 2 2 2
4 4 4 3 3
5 5 5 5 4

More Answers (0)

Products


Release

R2017a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!