Reading a text file

3 ビュー (過去 30 日間)
Slobodan Djordjevi?
Slobodan Djordjevi? 2011 年 11 月 21 日
Hey everyone!
I have a question regarding textscan[]; command.
I have a file and I want to read it, but somehow I can't get it to read the I want to. The file looks like this :
CsF 33 734824
Al 22 734824
NaCl 77 734824
This is a mere sample and it updates now and then but that's not important. I want it to read in a way that each cell has an information about change. The change consists of element, mass and MatLab date number. So in this case a cell array would be "CsF 33 734824" or {3x1}. I have only been able to read it nicely, but the problem is that all three informations get put into one cell.
So I have whitespace and newline separators.
fid = fopen('Spojine.txt');
R = textscan(fid, '%s', 'delimiter', '\n');
fclose(fid);
If someone would be nice enough to assist my code, that would be lovely! :)

採用された回答

Fangjun Jiang
Fangjun Jiang 2011 年 11 月 21 日
I recommend Jan's approach because it puts string into sting and numerical to numerical. But if you want it, you can use reshape().
fid = fopen('test.txt');
R = textscan(fid, '%s');
S=reshape(R{:},3,[]).';
fclose(fid);

その他の回答 (2 件)

Jan
Jan 2011 年 11 月 21 日
fid = fopen('Spojine.txt');
R = textscan(fid, '%s %f %f', 'delimiter', ' ')
fclose(fid);
Then the names are found in the cell string R{1}, and the values as vectors in R{2} and R{3}.
  2 件のコメント
Slobodan Djordjevi?
Slobodan Djordjevi? 2011 年 11 月 21 日
Thanks for a quick reply!
This is exactly what I don't want :)
I'm sorry you misunderstood.
Your code simply puts columns into cell string and 2 vectors.
I want it to read rows. The exact opposite.
Jan
Jan 2011 年 11 月 21 日
@Slobodan: Waht about posting exactly, what you want as output? The "exact opposite" is not well defined.

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


Slobodan Djordjevi?
Slobodan Djordjevi? 2011 年 11 月 21 日
Thank you both!
Reshape is the thing I was looking for.
Jan, you are right, it would create problems later on if I had strings and numeric data in one.
I should have done it with structers, but I think I can avoid those.
Cheers from Slovenia.
Slobodan
  1 件のコメント
Fangjun Jiang
Fangjun Jiang 2011 年 11 月 21 日
Or you could avoid using reshape,
%%
fid = fopen('test.txt');
R = textscan(fid, '%s %s %s','collectoutput',true);
fclose(fid);

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

カテゴリ

Help Center および File ExchangeLaTeX についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by