如何从矩阵中删除NAN值?

3,919次观看(最近30天)
布兰登·沃克
布兰登·沃克 on 18 Feb 2015
编辑: Stephen23 on 15 Aug 2020
到目前为止,我的代码在下面。我有代码,以便它跳过前19行,并从第20行开始。但是,我需要删除数据中的NAN值,例如列= [10; 0.04500; 0; 0; nan; nan; nan]。我必须删除NAN的跑步行,只是没有删除它们。我不确定什么不起作用。如何解决我的问题?
谢谢
fid = fopen('filename.txt');
行= textscan(fid,'%s',“定界符”,'\ n');
fclose(fid);
列= cellfun(@(x)textscan(x,'%F',“定界符”,'\t','CollectOutput',1)...
,行{1,1}(20:end,:));
支撑材(isnan(fid(:,1)),:) = [];

接受ed Answer

Stephen23
Stephen23 on 18 Feb 2015
编辑:Stephen23 on 15 Aug 2020
该代码有多个需要解决的问题。这里有几件事要改进:
  • Thefopen文件指出支撑材is aninteger file identifier .... The variable支撑材does notcontainthe file data, it is merely a参考到打开文件。它也是标量值。因此,您试图索引支撑材as if it were a data array doesn't make any sense.
  • Over-complicated method of reading a text file: first textscan, then cellfun calling textscan again, all just to avoid some header lines? Instead you should readtextscan的文档,并使用HeaderLines选择,这样:
fid = fopen('filename.txt','r');
data = textscan(fid,'%F',“定界符”,'\t','HeaderLines',20);
FCLOSE(FID)
我还删除了 CollectOutput option, as this is superfluous if there is only one format specifier. For the same reason the delimiter doesn't really make sense either. If you have multiple values per line, then you need to specify them in the formatSpec : there are plenty of examples in the documentation.
Starting in R2018b, you can use the “rmmissing” function to remove “NaN” values from an array. For example, consider the following:
A = [1,NaN,2];
B = rmmissing(A)
The result is the vector “B = [1 2]”.
在R2018A及以后,使用“ ISNAN”函数:
A = [1,NaN,2];
B = A(~isnan(A))
5 Comments
Walter Roberson
Walter Roberson 2019年10月31日
x =列{2};
X(isnan(X)) = [];

Sign in to comment.

更多答案(3)

Erik S.
Erik S. on 18 Feb 2015
编辑:Per Isakson 2018年5月25日
You can you something like this
ind = ~isnan(Columns);
Columns=Columns(ind);

Cong Dong Ngoc Minh
Cong Dong Ngoc Minh on 16 Jun 2020
你可以这样尝试
idx =isnan(Columns)
Columns(idx,:) = []

Berfin Karabulut
Berfin Karabulut on 14 Aug 2020
或者,您可以简单地使用“ Omitnan”功能?
1 Comment
Walter Roberson
Walter Roberson on 15 Aug 2020
omitnan is not a Mathworks function. It is an option that can be used in some functions that are not relevant to the question asked.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

开始狩猎!