1

I want to read some data from a text file but I don't know how to do this. I know that I can read text files like this

fid=fopen('data.txt');
A = textscan(fid,'%s')

which returns

A =
{
  [1,1] =
  {
    [1,1] = drink
    [2,1] = water
    [3,1] = drink
    [4,1] = eat
    [5,1] = drink
    [6,1] = spoon
    [7,1] = water
    [8,1] = drink
    [9,1] = water
    [10,1] = drink
  }
}

the text file looks like this

drink water drink
eat drink spoon
water drink water drink

But I want to store the data in a cell array like this

A =
{
  [1,1] =
  {
    [1,1] = drink
    [1,2] = water
    [1,3] = drink
  }
  [1,2] =
  {
    [1,1] = eat
    [1,2] = drink
    [1,3] = spoon
  }
  [1,3] =
  {
    [1,1] = water
    [1,2] = drink
    [1,3] = water
    [1,4] = drink
  }
}

How can i solve this?

5
  • Double check the expected output? Commented Oct 29, 2014 at 20:52
  • What do you mean wirh double check the output? Commented Oct 29, 2014 at 21:00
  • 1
    A[1,1] has three drink cells and I am assuming [1,1] corresponds to the first row of the text file that has only two drink Commented Oct 29, 2014 at 21:02
  • We are in super hurry, aren't we? Double check again? Commented Oct 29, 2014 at 21:07
  • A[1,3] feels neglected too. Reminds me I need some drink too, and by that I mean just water. Commented Oct 29, 2014 at 21:09

1 Answer 1

1

You can use a combination of importdata and regexp with 'Split' option -

out = cellfun(@(x) regexp(x,'\s','Split'),importdata(text_filename,'\n'),'un',0).'

Output -

out{1,1}
ans = 
    'drink'    'water'    'drink'
out{1,2}
ans = 
    'eat'    'drink'    'spoon'
out{1,3}
ans = 
    'water'    'drink'    'water'    'drink'
Sign up to request clarification or add additional context in comments.

13 Comments

thanks but this doesn't really work. Im fairly new to matlab. I tried your solution an got an error: 'un' syntax error. Could you please explain me what this 'un' means
@user2348157 Try replacing that 'un' with 'UniformOutput' and let me know how it goes? That 'un' is like a short-hand for that.
@user2348157 For more info on that, please refer to the official doc page - mathworks.in/help/matlab/ref/cellfun.html
After replacing it i didn't get the error. But I get this now cellfun: C must be a cell array. I am not sure if I understand this right. Instead of using A=textscan... I use the code you posted and I should get the cell array?
@user2348157 Did you edit text_filename with the path to the text file? You are supposed to do that. So, it would be - out = cellfun(@(x) regexp(x,'\s','Split'),importdata('data1.txt','\n'),'un',0).', if data1.txt is the name of the text file in the working directory.
|

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.