Any
Any

Reputation: 75

textscan introduces additional zeros in output array

I have a .txt file like this:

ord,cat,1

ord,cat,1

ord,cat,3

ord,cat,1

ord,cat,4

I know the number of entries for each row (comma separated) but not the number of rows. I need to import the number of the following car in an array. I wrote this:

fid=fopen(filename)

A=textscan(fid,'%s%s%d','Delimiter',',')

But i get this

A =  {17x1 cell}    [16x1 int32]

where the number of cells is clearly wrong. When i try to read

A{3}

i get

ans =

       0
       0
       0
       0
       0
       1
       0
       1
       0
       3
       0
       1
       0
       4

I'm really interested just in the integer array, but maybe can be useful to show you also:

A{1}

ans = 

'{\rtf1\ansi\ansicpg1252\cocoartf1187\cocoasubrtf400'
'{\fonttbl\f0\fswiss\fcharset0 Helvetica;}'
'{\colortbl;\red255\green255\blue255;}'
[1x75  char]
[1x102 char]
'\f0\fs24 \cf0 ord'
'\'         
'ord'       
'\'         
'ord'       
'\'         
'ord'       
'\'         
'ord'       
'}'         

A{2}

ans = 

''
''
''
''
''
'cat'
''
'cat'
''
'cat'
''
'cat'
''
'cat'

Ok,I think there was a format mistake of some kind in the input file. I deleted it and created a new .txt file and the code above works fine.

Upvotes: 0

Views: 139

Answers (1)

nkjt
nkjt

Reputation: 7817

You're not giving the right format command to textscan.

A=textscan(fid,'%s%d','Delimiter',',')

'%s%d' here means "read one string, then one integer". So it will probably sit there reading string-integer-string-integer (or trying to), and the "0"s arise from errors where

Since you have three entries per line, try instead:

A=textscan(fid,'%s%s%d','Delimiter',',')

Your numbers should be in A{3}.

If you don't need the first two columns, you can also skip over those fields:

A=textscan(fid,'%*s%*s%d','Delimiter',',')

Upvotes: 2

Related Questions