0

I have a problem while reading an input file in Matlab. It appears that all the rows have one parameter input except for the last one which is a vector:

INPUT FILE 
--------------
Field1: number
Field2: text (one word)
Field3: number
Field4: number
Field5: number
Field6: number
Field7: vector

The code I have implemented looks like:

fid = fopen('input.inp','r');
A = textscan(fid,'%s %f','Delimiter','\t','headerLines',2);
data = cat(2,A{:});

I would like some help to deal with the fact that I have some text/number cases and also to deal with the vector form the last row. Thanks

1
  • It would be much better if you included real data. For example, what does your vector look like in the file? Commented Nov 17, 2014 at 12:34

1 Answer 1

2

Is this what you are looking for...?

I think you have to use %s %s as a format to text scan and not a float because a vector cannot be converted to a float for example.

I changed this A = textscan(fid,'%s %s','Delimiter','\t'); to include %s %s. Also, I think you want to concatenate along the first dimension rather than the second.

I think you actually want to create a key/value pair of the input file rather than just reading each row into a cell but you don't state that.

INPUT FILE 
--------------
Field1: 1
Field2: two
Field3: 3
Field4: 4
Field5: 5
Field6: 6
Field7: [7 8 9]


fid = fopen('D:\tmp\t.txt','r');
A = textscan(fid,'%s %s','Delimiter','\t','headerLines',2);


cat(1,A{:})
ans =
{
  [1,1] = Field1: 1
  [2,1] = Field3: 3
  [3,1] = Field5: 5
  [4,1] = Field7: [7 8 9]
  [5,1] = Field2: two
  [6,1] = Field4: 4
  [7,1] = Field6: 6
}

If you want to create a key/value pair, then you can split them into key and value with a loop that you can use with the Container class if needed. You have to filter your strings a bit (e.g remove colons etc) but you get the gist.

keySet = {};
valueSet = {};
for (n=1:size(A2,1))
    s = A2{n};
    ind = strfind(s,' ');  
    keySet{n} = s(1:ind(1));
    valueSet{n} =s(ind(1):end);
end

The output is

keySet =
{
  [1,1] = Field1:
  [1,2] = Field3:
  [1,3] = Field5:
  [1,4] = Field7:
  [1,5] = Field2:
  [1,6] = Field4:
  [1,7] = Field6:
}

valueSet =
{
  [1,1] =  1
  [1,2] =  3
  [1,3] =  5
  [1,4] =  [7 8 9]
  [1,5] =  two
  [1,6] =  4
  [1,7] =  6
}

From the Container class doc:

mapObj = containers.Map(keySet,valueSet)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.