user3473243
user3473243

Reputation: 65

Matlab: How to Insert 'NaN' in every n-rows

This is just a very simple example to show my problem.

a=ones(5)  

How can i insert NaN after every two rows like:

I know the way to do this simple example is:

b(:,1:5)=NaN

[a(1:2,:);b;a(3:4,:);b;a(end,:)]

But the problem is if the martrix is 60000-by-200 (may be more larger), so how can i insert 'NaN' after every two rows.

Thanks so much.

Upvotes: 2

Views: 1585

Answers (3)

ben
ben

Reputation: 1390

You can do it like this:

>> a= [ 1 2 3 4 5 6 7 8 9]
a =
     1     2     3     4     5     6     7     8     9

>> b = nan(floor(length(a)/2),1)'
b =
   NaN   NaN   NaN   NaN

>> a_new = zeros(1, length(a)+length(b))
a_new =

     0     0     0     0     0     0     0     0     0     0     0     0     0

>> b_i = 3:2:length(a)
b_i =

     3     5     7     9

>> a_new(b_i+(0:length(b_i)-1)) = b
a_new =
     0     0   NaN     0     0   NaN     0     0   NaN     0     0   NaN     0

>> a_new(~isnan(a_new))=a
a_new =
     1     2   NaN     3     4   NaN     5     6   NaN     7     8   NaN     9

Upvotes: 0

Luis Mendo
Luis Mendo

Reputation: 112759

a = ones(5); %// example data
n = 2; %// number of rows

N = floor(size(a,1)*(1+1/n)); %// final number of rows
ind = mod(1:N, n+1) ~= 0; %// logical index for non-NaN rows
b = NaN(N,size(a,2)); %// initiallize result to NaN
b(ind,:) = a; %// fill in non-NaN rows

Upvotes: 3

Pursuit
Pursuit

Reputation: 12345

I can't think of an easy, one-line type solution. It can be done in a pretty tight loop though.

a = ones(5);

a_with_nans = nan(floor(size(a,1)*(3/2)), size(a,2)); %Start with all nans in a larger matrix
for ix = 1:2:size(a,1)
    a_with_nans(ix*3/2-(1/2),:) = a(ix,:);
    if ix+1<=size(a,1)
        a_with_nans(ix*3/2-(1/2)+1,:) = a(ix+1,:);
    end
end

Then:

a_with_nans =
     1     1     1     1     1
     1     1     1     1     1
   NaN   NaN   NaN   NaN   NaN
     1     1     1     1     1
     1     1     1     1     1
   NaN   NaN   NaN   NaN   NaN
     1     1     1     1     1

Upvotes: 1

Related Questions