我有以下矩阵
A = [ 0 0
0 0
1 -1
NaN NaN
NaN NaN
0 0
NaN NaN
NaN NaN]
我想用它上面的行替换所有NaN
行。对于上面的矩阵,这将是
A = [0 0
0 0
1 -1
1 -1
1 -1
0 0
0 0
0 0]
答案 0 :(得分:4)
一个想法是首先创建一个压缩矩阵B
,它不包含NaN
的行,然后再次将此矩阵展开为相同的长度作为原始矩阵:
mask = any(isnan(A), 2);
B = A(~mask, :);
result = B(cumsum(~mask), :);
答案 1 :(得分:2)
我不确定这是否可以被矢量化......更简单的解决方案可能是一个循环:
newRow = [];
nans = isnan(A(:,1));
for ii = 1:size(A,1)
if nans(ii)
%# first row might be NaN -- skip it
if ii==1
continue; end
%# for all other rows:
if isempty(newRow)
newRow = A(ii-1,:); end
A(ii,:) = newRow;
else
newRow = [];
end
end