MATLAB Answers

How to fscanf a text file of characters to a string array/vector, but not a 1x1 string?

3 views (last 30 days)
Leon Chan
Leon Chan on 22 Apr 2021
Edited: Leon Chan on 23 Apr 2021
I want to use fscanf to convert sample.txt to a 6x1 string array (or 1x6 also fine) like below:
data=["apple"; "orange"; "banana'; "grapes"; "watermelon"; "mango"]
I used the following code but fails:
fid=fopen('sample.txt', 'rt')
data=fscanf(fid, '%s\n')
fclose(fid);
Matlab shows the output like this:
data = 'appleorangebananagrapeswatermelonmango'
How to fix the problem? Thank you for the assistance.

More Answers (1)

Mathieu NOE
Mathieu NOE on 22 Apr 2021
hello try this :
fid=fopen('sample.txt', 'rt')
data=split(fscanf(fid,'%c'))
fclose(fid);
% gives :
data = 6×1 cell array
{'apple' }
{'orange' }
{'banana' }
{'grapes' }
{'watermelon'}
{'mango' }

Community Treasure Hunt

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

Start Hunting!