Importdata not importing as a cell array and instead as a column vector

8 views (last 30 days)
Hi,
I have this input file as a .txt here
2
0.0 1.0 6.283185307
0.0 -1.0 -6.283185307
But when I use importdata, it gives me a line vector as stated:
data =
2.0000
0
1.0000
6.2832
0
-1.0000
-6.2832
I reckon it is due to the first line of the .txt file being a single integer. I can't change the contents of the .txt file.
Any idea how to fix this?
  1 Comment
dpb
dpb on 7 Sep 2019
Well, it depends on what you think is a valid "fix". You haven't specified what you would expect.
MATLAB can't store "jagged" arrays, so you'll have to do something about the fact there's only one element in the first record and three in the two other records (what about the rest of the file or is this all there is?).
Without more context of what the data are in terms of use/meaning, it's not easy to suggest the better of the various alternatives which could include the first record being a standalone variable on its own while the rest is a Nx3 array, or a cell array containing the one element as its first element and the array or ...

Sign in to comment.

Accepted Answer

Bhargavi Maganuru
Bhargavi Maganuru on 10 Sep 2019
You can use textscan function to read data from an open text file into a cell array.
f=fopen(‘a.txt’);
data=textscan(f,'%f%f%f',2)
Hope this helps!
  1 Comment
dpb
dpb on 10 Sep 2019
NB that solution will only read the first two records; altho does return NaN for the second and third elements of the first record in the first element of the second two cell arrays.
Probably if going this route more easily used would be to 'collectoutput' so have one cell array--
>> data=textscan(fid,repmat('%f',1,3),2) % sample, read only two records
data =
1×3 cell array
{2×1 double} {2×1 double} {2×1 double}
>> [data{1} data{2} data{3}]
ans =
2.0000 NaN NaN
0 1.0000 6.2832
>> clear data
>> frewind(fid)
>> data=textscan(fid,repmat('%f',1,3),'collectout',1) % read all file, collect output
data =
1×1 cell array
{3×3 double}
>> data{:}
ans =
2.0000 NaN NaN
0 1.0000 6.2832
0 -1.0000 -6.2832
>>
OP will have to decide whether the first element belongs in the cell array w/ the remainder and then to remember to not process the NaN or should read it first...
>> frewind(fid)
>> n=cell2mat(textscan(fid,'%f',1))
n =
2
>> data=cell2mat(textscan(fid,repmat('%f',1,3),'collectout',1))
data =
0 1.0000 6.2832
0 -1.0000 -6.2832
>>
which leaves one with two "regular" double variables rather than cell array(s).

Sign in to comment.

More Answers (0)

Categories

Find more on Large Files and Big Data in Help Center and File Exchange

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!