How to convert a text file to 0's and 1's

3 次查看(过去 30 天)
Hello
I've been trying during that past days to convert a text file that contains strings into 0's and 1's .
The file can be read using the fileread command, but the knot is, how can the file be converted to a 0's and 1's matrix in matlab ?!!
Example of the data:
T T1 T2 T3 T4 T5
r Soda-bottle White-Bread Oat-Meal Milk-organic Milk
r Bagles Croissants Soda-bottle Orange-Juice
r White-Bread
r Orange-Juice White-Bread Bagles Apple-Juice Milk
r Croissants Milk-organic Baguette Soda-bottle
r Milk Coffee
r Bread Beer-can
where not all the columns are filled, as for the above data the first line has all 1's for the 5 different customers and the second line has 4 1's and a 0 .
How can this be acheived using matlab ?

回答(1 个)

Rik
Rik 2020-8-1
编辑:Rik 2020-8-2
If you have a master-list you can use ismember to create a logical vector line by line. If you need an example, you should post the list of items.
Edit:
Since apparently you want to more or less count the number of items, this code should do the trick.
You can install the readfile function through the addon manager, or get it from the FEX here. Alternatively, you can read the file with your own code and put each line in a cell: strsplit(data,'\n') should get you there.
data=readfile('https://www.mathworks.com/matlabcentral/answers/uploaded_files/340423/data%20250.txt');
data(1)=[];%remove header line
output=false(numel(data),5);
for n=1:numel(data)
tmp=strsplit(data{n});
tmp=~cellfun(@isempty,tmp);
tmp(1)=[];%remove 'r'
output(n,1:numel(tmp))=tmp;
end
  1 个评论
Hasan Bazzoun
Hasan Bazzoun 2020-8-2
attached is the complete data file.
the idea is to convert the data in the file to 0's and 1's
T T1 T2 T3 T4 T5
1 1 1 1 1
1 1 1 1 0
1 0 0 0 0
as per the data in the file.

请先登录,再进行评论。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by