フィルターのクリア

How to detect, open and process nxm matrices?

2 ビュー (過去 30 日間)
Ekin
Ekin 2013 年 9 月 15 日
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!

採用された回答

Jan
Jan 2013 年 9 月 17 日
編集済み: Jan 2013 年 9 月 17 日
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);

その他の回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 9 月 15 日
If your files are not big, you can use
v=dlmread('file.txt')
  3 件のコメント
Ekin
Ekin 2013 年 9 月 15 日
And files will be really big.
Jan
Jan 2013 年 9 月 17 日
編集済み: Jan 2013 年 9 月 17 日
uigetfile does not open files, but determine the file name only. Of course you can apply Azzi's suggestion together with your uigetfile part.
Some users think, that 1MB is big, others use this term for 20 TB files.

サインインしてコメントする。


Walter Roberson
Walter Roberson 2013 年 9 月 15 日
textscan(fp, '%f')
is fine to read either format. End-of-line is considered to be "whitespace" for textscan(), so it will be fine without you having to code differently for the two situations.
If it is important that you process the two forms in different ways, then:
currentloc = ftell(fp); %find out where we are now
small_input = fread(fp, 20, '*uint8'); %read a little
fseek(fp, currentloc, 'bof'); %go back to where we were
if any(small_input == 10) %control J, newline, \n
%there was a newline, so it is n x 1 rather than 1 x n.
...
else
%it was 1 x n
end
  2 件のコメント
Ekin
Ekin 2013 年 9 月 17 日
編集済み: Ekin 2013 年 9 月 17 日
It is not important to process them in different ways for me, i just want to process both of them. I am currently using
textscan(fp, '%f')
It works fine with mx1 matrices, but gives error when input is 1xn.
Walter Roberson
Walter Roberson 2013 年 9 月 17 日
What error do you get?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLarge Files and Big Data についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by