Append values from textscan into cell array literately in a loop

12 ビュー (過去 30 日間)
Ted Hein
Ted Hein 2019 年 3 月 7 日
回答済み: Stephen23 2019 年 3 月 8 日
Currently I have a txt file with data as shown below:
A11
Temperature=20 Weight=120 Speed=65
B13
Temperature=21 Weight=121 Speed=63
F24
Temperature=18 Weight=117 Speed=78
D43
Temperature=16 Weight=151 Speed=42
C32
Temperature=15 Weight=101 Speed=51
I would like to read the value into a cell array and convert it as matrix as formated below:
20 120 65
21 121 63
18 117 78
16 151 42
15 101 51
Below is my code:
% At first I read the data into a 1 column array
fid=fopen('file.txt');
tline = fgetl(fid);
tlines = cell(0,1);
while ischar(tline)
tlines{end+1,1} = tline;
tline = fgetl(fid);
end
fclose(fid);
% Then I check the size of the cell array
CellSize = size(tlines);
DataSize = CellSize(1,1);
% At last I setup a loop and literately read and input the values
Data = cell(0,3);
for i = 1:DataSize
Data{end+1,3} = textscan(tlines{i,1},'Temperature=%f Weight=%f Speed=%f');
end
However, I got 10x3 empty cell array.
[] [] *1x3cell*
[] [] *1x3cell*
[] [] *1x3cell*
[] [] *1x3cell*
[] [] *1x3cell*
[] [] *1x3cell*
[] [] *1x3cell*
[] [] *1x3cell*
[] [] *1x3cell*
[] [] *1x3cell*
I know the problem comes from the input of textscan value into the cell array.
Can you help me fix the problem?
Also how can I toss the empty value if the data doesn't contain the specific format.
  2 件のコメント
Bob Thompson
Bob Thompson 2019 年 3 月 7 日
What is contained within the 1x3 cells? Are those also empty?
Ted Hein
Ted Hein 2019 年 3 月 8 日
yes, they are all empty

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

採用された回答

Stephen23
Stephen23 2019 年 3 月 8 日
>> str = fileread('test.txt');
>> reshape(sscanf(str,'%*[^=]=%f'),3,[]).'
ans =
20 120 65
21 121 63
18 117 78
16 151 42
15 101 51

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by