How to read data from a file with fixed format?
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Erivelton Gualter
am 16 Nov. 2019
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.
Antworten (2)
Bhaskar R
am 16 Nov. 2019
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 Kommentare
Walter Roberson
am 16 Nov. 2019
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.
0 Kommentare
Siehe auch
Kategorien
Mehr zu String Parsing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!