function data = readMM_2D(file,nrows,flagstr)
%Read 2-D matrix saved with Mathematica 'Put' command.
%READMM_2D(file,nrows) reads data from the full path+filename specified by
%'file' and parses the data into the number of rows specified by 'nrows'.
%
% If the number of rows is specified the function uses TXT2MAT to read a
% Mathematica formatted 2D data array. If number of rows is not specified,
% or if TXT2MAT is not available, the function reads the file with TEXTREAD
% and automatically determines the number of rows and columns for the input
% data.
%
% Inputs:
% file -- string variable; fully specified filename
% nrows -- numeric scalar; number of rows in data file
% flagstr -- 'fast' specifies TXT2MAT algorithm (default)
% 'slow' specifies TEXTREAD algorithm
%
% Example:
% numrows = 1248;
% myfile = 'C:\somefile.txt';
% A = readMM_2D(myfile,numrows);
%
% ans = <1248x1248 double>
%
% David Sedarsky
% November, 2008
if nargin == 0,
[FileName,PathName] = uigetfile('*.*','Select data file');
% If "Cancel" is selected then return
if isequal([FileName,PathName],[0,0])
return
else
file = fullfile(PathName,FileName);
end
nrows = 0;
flagstr = 'slow';
end
if nargin == 1,
nrows = 0;
flagstr = 'slow';
end
if nargin == 2,
flagstr = 'fast';
end
if ~isnumeric(nrows)
flagstr = 'slow';
end
%fast read process based on TXT2MAT
if strcmpi(flagstr,'fast'),
% disp('running fast routine');
if exist('txt2mat')==2,
a = txt2mat(file,...
'ReadMode','block',...
'NumColumns',nrows,...
'ReplaceChar',{'{}, '});
else
warning('TXT2MAT not found, using slower TEXTREAD process.');
flagstr = 'slow';
end
end
if strcmpi(flagstr,'fast'),
%reshape matrix
data = reshape(a,nrows,nrows).';
end
%slow read process based on TEXTREAD
if ~strcmpi(flagstr,'fast'),
% disp('running slow routine');
%read entire file as cell string
a = textread(file,'%s','delimiter',',');
%search for first '}' character (indicates the end of a column)
for count=1:length(a)
if ~isempty(strfind(cell2mat(a(count)),'}'))
break
end
end
ncols = count;
nrows = length(a)/ncols;
%clean braces '{' and '}' from data
a = strrep(a,'{','');
a = strrep(a,'}','');
%convert cell array to char
a = char(a);
%convert string array to numeric
a = str2num(a);
%reshape matrix
data = reshape(a,ncols,nrows);
end