While Divakar's answer works if you don't have any values of zero in your text file, that's may not generally be the case. For example, if your text array was
1 2 3
4 0
5 6 0 7 8
then Divakar's result would be:
1 2 3 nan nan
4 nan nan nan nan
5 6 nan 7 8
whereas you really want:
1 2 3 nan nan
4 0 nan nan nan
5 6 0 7 8
The easiest way to implement this is to open up the dlmread function (just type dlmread into the text editor and press Ctrl+D to open it up). Make sure to save this file as a separate file in the directory you're working in with a different name (i.e. dlmread_nan.m).
Go down to this part of the code (line 126 in my version):
if isempty(delimiter)
result = textscan(fid,'',nrows,'headerlines',r,'headercolumns',c,...
'returnonerror',0,'emptyvalue',0, 'CollectOutput', true);
else
delimiter = sprintf(delimiter);
whitespace = setdiff(sprintf(' \b\t'),delimiter);
result = textscan(fid,'',nrows,...
'delimiter',delimiter,'whitespace',whitespace, ...
'headerlines',r,'headercolumns',c,...
'returnonerror',0,'emptyvalue',0,'CollectOutput', true);
end
and change the value after 'emptyvalue' in both cases to NaN instead of 0. Save the file. It should look like this:
if isempty(delimiter)
result = textscan(fid,'',nrows,'headerlines',r,'headercolumns',c,...
'returnonerror',0,'emptyvalue',NaN, 'CollectOutput', true);
else
delimiter = sprintf(delimiter);
whitespace = setdiff(sprintf(' \b\t'),delimiter);
result = textscan(fid,'',nrows,...
'delimiter',delimiter,'whitespace',whitespace, ...
'headerlines',r,'headercolumns',c,...
'returnonerror',0,'emptyvalue',NaN,'CollectOutput', true);
end
To get your array, use this:
result = dlmread_nan('text.txt', ' ');
%%//This will give you exactly what you're looking for.
It's a little cumbersome, but by copying from MATLAB's library, it'll probably be a lot more robust and error-free than writing it from scratch yourself.