MATLAB: How to detect, open and process nxm matrices

file openmatricesmatrixopentextscan

Hi i have a code to open .txt files with nx1 matrices, it works very well:
[filename1,filepath1]=uigetfile({'*.txt*','Text Files'},...
'Select Data File 1');
cd(filepath1);
fp= fopen(filename1);
fgets(fp);
A = textscan(fp, '%f');
fclose(fp);
result=A{:};
But i want to open 1xm matrices with this code also. Do do this, i though to create an if-else structure to deteckt if the data matrix is nx1 or 1xm and then textscan it with textscan(fp, '%f') or textscan(fp, '%??'). Or is there another way to make this without creating an if-else structure? Thanks in advance!

Best Answer

fp = fopen(filename1);
if fp == -1, error('Cannot open %s', filename1); end
fgets(fp); % Skipping a header line?!
pos = ftell(fp);
tmpLine = fgets(fp); % Read first line
tmpData = sscanf(tmpLine, '%g ', Inf);
nDataPerLine = length(tmpData);
fseek(fp, pos, -1); % Spool one line back
Data = fscanf(fp, '%g ', [nDataPerLine, Inf]);
fclose(fp);