How to read data from a file with fixed format?

4 次查看(过去 30 天)
I want read data from a file and assign the data into an array. The file name is test1, and the data format is [1,2,3,4,5,6,7,8,9,10,11]. I want to import the data into an array. I have tried A=importdata(test1); I would expect that A is a 1x11 array, and A(1)=1, A(2)=2, etc. However, the result is that A is a 1x1 array, and the only element of A is [1,2,3,4,5,6,7,8,9,10,11].
  1 个评论
Erivelton Gualter
Erivelton Gualter 2019-11-16
You can assign directly to a variable. Like the following:
array = [1,2,3,4,5,6,7,8,9,10,11]
disp(size(array))
Then, you will see that size is 1x11.
Upload your file to see what is going on which this array of 1x1.

请先登录,再进行评论。

回答(2 个)

Bhaskar R
Bhaskar R 2019-11-16
importdata gives you data in cell data type.
A=importdata(test1);
A = A{1}; % get the data from cell
% now you will get values as you required
A(1)
A(2) % so on
  2 个评论
J Han
J Han 2019-11-16
Then A still have the square brackets in it. Is there a way to get rid of the square bracket!

请先登录,再进行评论。


Walter Roberson
Walter Roberson 2019-11-16
importdata() is going to treat the first thing on the line as numeric (skipping the leading '[') but it treats everything else on the line as text.
readtable() without using detectImportOptions is a bit better: it identifies everything in the middle as numeric, but detects the first and last as text.
readtable with detectImportOptions decides that the entire thing is one character vector.
The simplest way to handle something like that is to read the text in and str2num() it. This is, though, risky: if the file contains system('deltree C:\') then str2num() will try to delete all of your files.
A better approach:
sscanf(erase(fileread('YourFileName.txt'),{'[',']'}),'%f%*[, ]')
This removes [ and ] characters and reads as many number-like things as it can, with numbers terminated by commas or blanks -- so for example, '[1 2 3 4, 5, 6]' would be handled as well.

类别

Help CenterFile Exchange 中查找有关 String Parsing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by