How to read data from a file with fixed format?

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

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일

0 개 추천

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!
Bhaskar R
Bhaskar R 2019년 11월 16일
Can you share your file(test1)?

댓글을 달려면 로그인하십시오.

Walter Roberson
Walter Roberson 2019년 11월 16일

0 개 추천

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.

카테고리

도움말 센터File Exchange에서 Data Import and Analysis에 대해 자세히 알아보기

질문:

2019년 11월 16일

답변:

2019년 11월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by