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

조회 수: 5 (최근 30일)
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
dpb
dpb 2019년 9월 7일
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 ...

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

채택된 답변

Bhargavi Maganuru
Bhargavi Maganuru 2019년 9월 10일
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
dpb
dpb 2019년 9월 10일
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).

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by