Align multiple columns by their center index value

I have a matrix with 3 columns with different number of values in each (each column has an odd number of values) and i'd like to align the columns by their center index value. e.g. something like below, underlined are center values per column
Original matrix
1 1 1
2 2 2
3 3 3
NaN 4 4
NaN 5 5
NaN NaN 6
NaN NaN 7
NaN NaN NaN
NaN NaN NaN
Aligned matrix
NaN NaN NaN
NaN NaN 1
NaN 1 2
1 2 3
2 3 4
3 4 5
NaN 5 6
NaN NaN 7
NaN NaN NaN
I am a newcomer to Matlab, any tips on how to go about tackling this is great appreciated!!

 Accepted Answer

DGM
DGM on 2 May 2021
Edited: DGM on 2 May 2021
Something like this:
A = [1 1 1;
2 2 2;
3 3 3;
NaN 4 4;
NaN 5 5;
NaN NaN 6;
NaN NaN 7;
NaN NaN NaN;
NaN NaN NaN]
B = A;
shiftamt = floor(sum(isnan(A),1)/2);
% circshift() doesn't take vector k, so we need a loop
for n = 1:size(A,2)
B(:,n) = circshift(B(:,n),shiftamt(n),1);
end
B
gives:
A =
1 1 1
2 2 2
3 3 3
NaN 4 4
NaN 5 5
NaN NaN 6
NaN NaN 7
NaN NaN NaN
NaN NaN NaN
B =
NaN NaN NaN
NaN NaN 1
NaN 1 2
1 2 3
2 3 4
3 4 5
NaN 5 6
NaN NaN 7
NaN NaN NaN

More Answers (0)

Products

Release

R2021a

Tags

Asked:

on 1 May 2021

Commented:

on 2 May 2021

Community Treasure Hunt

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

Start Hunting!