writing each line of a text file in a cell array

5 ビュー (過去 30 日間)
Shima Asaadi
Shima Asaadi 2016 年 3 月 23 日
編集済み: Kirby Fears 2016 年 3 月 23 日
I try to write a text file in a cell array in MATLAB, each line consists of a number of strings,in to a cell array, and at last the whole file in a cell. the following code works well, but I am looking for a shorter and efficient way of implementing the code: (because I have many documents to apply to this code)
fileToRead = 'myfile.txt';
fid = fopen(fileToRead,'rt');
tmp = textscan(fid, '%s', 'Delimiter', '\n');
fclose(fid);
C=cell(1,1);
size(tmp{1,1})
k=1;
for i=1:size(tmp{1,1})
temp = strsplit(tmp{1,1}{i,1})
C{k,1}=temp;
k=k+1;
end
Does anyone know a better way?
Thanks
  1 件のコメント
dpb
dpb 2016 年 3 月 23 日
I'm not following what you want as the end result. I small sample file and the desired output would help...

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

採用された回答

Kirby Fears
Kirby Fears 2016 年 3 月 23 日
編集済み: Kirby Fears 2016 年 3 月 23 日
Hi Shima,
From context clues, I'm guessing "myfile.txt" is a space-delimited table of data. Your approach is useful if you don't know exactly how many columns are in the file.
I made a utility function called delimread which you might find very helpful. You can download delimread and include it in your matlab path in order to call it.
The below example will read a space-delimited text file into a correctly sized cell array without specifying the number of columns in the file:
% Read file as raw text
fileToRead = 'myfile.txt';
result = delimread(fileToRead,' ','raw');
% display result
disp(result.raw);
If this doesn't work for you, please post a small sample of your text file so I can give a more accurate response.
Hope this helps.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Import and Export についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by