How can I delete the rows if they have a NaN value?
2 次查看(过去 30 天)
显示 更早的评论
Hello all,
My problem is kinda cheezy but I still can't solve the problem so here it is;
So my codes I wrote so far are;
load carsmall
x=[MPG]
y=[Weight]
and I'd likte to delete the rows which contains NaN in my x value. Long story in short I'd like to delete the rows 11,12,13,14,15 and 18 since they have NaN values.
Any helps are appreciated,
Regards,
0 个评论
采纳的回答
更多回答(1 个)
Khalid Mahmood
2021-4-15
编辑:Khalid Mahmood
2021-4-15
Let Matrix A has NaN values, we want a matrix B which contains all rows of A except which have NaN values
function testNaNRemoval()
A = [ 1 5 8 ; -3 NaN 14;0 6 NaN ; 1 5 18];
B=remove_nan_rows(A)
end
function B = remove_nan_rows(A)
B=[];ib=1;
for i=1:size(A,1)
if any(isnan(A(i,:))), continue;end
B(ib,:)=A(i,:); ib=ib+1;
end
end
1 个评论
Khalid Mahmood
2021-4-15
This is a bit lengthy answer, but keep=~isnan(A); B=A(keep) also works.
Advantage of longer method is when we want mixed behaviour or our tailored processing
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!