Reputation: 173
I have a 3D matrix 't' of size 174x162x286 representing longitude x latitude x timestep. However, there are three timesteps missing in 't'. I need to insert a blank array at these specific places such that the end product will be 't' of size 174x162x289.
t(:,:,236)=NaN;
I do not want to shift the entire array.
Upvotes: 0
Views: 55
Reputation: 112659
You can do it in one go as follows:
t = randi(9, 2, 4, 7); % example data
ind_insert = [3 5 6 6]; % insert immediately after these 3rd-dim positions
[~, ind] = sort([1:size(t,3) ind_insert]); % exploits the fact that sorting is stable
t = cat(3, t, NaN(size(t,1), size(t,2), numel(ind_insert)));
t = t(:,:,ind);
Example: before:
t(:,:,1) =
3 7 4 7
3 8 8 1
t(:,:,2) =
6 9 5 5
4 1 4 7
t(:,:,3) =
3 5 2 5
8 1 7 2
t(:,:,4) =
4 2 3 3
6 7 9 7
t(:,:,5) =
2 1 7 4
3 6 5 6
t(:,:,6) =
6 6 2 3
7 9 7 2
t(:,:,7) =
6 5 7 6
5 6 4 4
After:
t(:,:,1) =
3 7 4 7
3 8 8 1
t(:,:,2) =
6 9 5 5
4 1 4 7
t(:,:,3) =
3 5 2 5
8 1 7 2
t(:,:,4) =
NaN NaN NaN NaN
NaN NaN NaN NaN
t(:,:,5) =
4 2 3 3
6 7 9 7
t(:,:,6) =
2 1 7 4
3 6 5 6
t(:,:,7) =
NaN NaN NaN NaN
NaN NaN NaN NaN
t(:,:,8) =
6 6 2 3
7 9 7 2
t(:,:,9) =
NaN NaN NaN NaN
NaN NaN NaN NaN
t(:,:,10) =
NaN NaN NaN NaN
NaN NaN NaN NaN
t(:,:,11) =
6 5 7 6
5 6 4 4
Upvotes: 3