将文本文件的内容插入变量中

时间:2014-10-10 19:40:29

标签: matlab

我想加载文本文件,使用ASCII字符,并将所有内容放入MATLAB中的varialbe中,这是我试过的代码:

f =fopen('tp.txt')

我得到的结果是1,然后每次执行此代码行时它都会递增。

然而,当我尝试:

f =load('tp.txt')

我收到此错误:

??? Error using ==> load
Number of columns on line 1 of ASCII file D:\Cours\TP\tp.txt
must be the same as previous lines.

Error in ==> TPTI at 3
f =load('tp.txt')

我的目标是计算每个charachter的出现次数,然后计算可能性和熵。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

试试这个:

%// Import file contents as a string
str = importdata('tp.txt'); %// each line is a cell
str = [str{:}]; %// concat all lines into a single string

%// Remove spaces. Maybe you want to remove other characters as well: punctuation...
str = regexprep(str, '\s', '');

%// Count frequency of each character:
freq = histc(double(str), 0:255); %// convert characters to ASCII codes and count