How do I read comma separated values from a .txt file in MATLAB using textscan()? -
i have .txt file rows consisting of 3 elements, word , 2 numbers, separated commas.
for example:
a,142,5 aa,3,0 abb,5,0 ability,3,0 about,2,0
i want read file , put words in 1 variable, first numbers in another, , second numbers in having trouble textscan
.
this have far:
file = [local_dir 'filetoread.txt']; fid_file = fopen(file,'r'); [words,var1,var2] = textscan(file,'%s %f %f','delimiter',','); fclose(fid_file);
i can't seem figure out how use delimiter textscan
.
horchler indeed correct. first need open file fopen
provides file id / pointer actual file. you'd use textscan
. also, need 1 output variable because each "column" placed separate column in cell array once use textscan
. need specify delimiter ,
character because that's being used separate between columns. done using delimiter
option in textscan
, specify ,
character delimiter character. you'd close file after you're done using fclose
.
as such, this:
file = [local_dir 'filetoread.txt']; f = fopen(file, 'r'); c = textscan(f, '%s%f%f', 'delimiter', ','); fclose(f);
take note formatting string has no spaces because delimiter flag take care of work. don't add spaces. c
contain cell array of columns. if want split columns separate variables, access right cells:
names = c{1}; num1 = c{2}; num2 = c{3};
these variables putting text provided in post file called filetoread.txt
:
>> names names = 'a' 'aa' 'abb' 'ability' 'about' >> num1 num1 = 142 3 5 3 2 >> num2 num2 = 5 0 0 0 0
take note names
cell array of names, accessing right name done doing n = names{ii};
ii
name want access. you'd access values in other 2 variables using normal indexing notation (i.e. n = num1(ii);
or n = num2(ii);
).
Comments
Post a Comment