这只是展示我问题的一个非常简单的例子。
a=ones(5)
如何在每两行之后插入NaN,如:
我知道做这个简单例子的方法是:
b(:,1:5)=NaN
[a(1:2,:);b;a(3:4,:);b;a(end,:)]
但问题是如果martrix是60000乘200(可能更大),那么我怎样才能插入' NaN
'每两行之后。
非常感谢。
答案 0 :(得分:3)
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
答案 1 :(得分:1)
我想不出一个简单的单线型解决方案。它可以在非常紧凑的循环中完成。
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
然后:
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
答案 2 :(得分:0)
你可以这样做:
>> 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