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

21 views (last 30 days)
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.

Accepted Answer

Stephen23
Stephen23 on 22 Apr 2021
str = readlines('sample.txt')
str = 6×1 string array
"apple" "orange" "banana" "grapes" "watermelon" "mango"

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' }

Categories

Find more on Convert Image Type in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!