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

17 次查看(过去 30 天)
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.

采纳的回答

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

更多回答(1 个)

Mathieu NOE
Mathieu NOE 2021-4-22
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' }

类别

Help CenterFile Exchange 中查找有关 Convert Image Type 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by