永发信息网

matlab怎么读取一个全是字符串的txt文件

答案:2  悬赏:30  手机版
解决时间 2021-01-24 16:21
  • 提问者网友:记得曾经
  • 2021-01-24 00:29
matlab怎么读取一个全是字符串的txt文件
最佳答案
  • 五星知识达人网友:枭雄戏美人
  • 2021-01-24 01:03
如有xxx.txt文档,其内容如下:
\begin{figure}
\centering
\includegraphics[width=0.7\textwidth]{fig1.eps}
\caption{\label{fig1} Experimentally known logarithm of $\beta$$^{-}$-decay half-lives, versus
logarithm of $Q$-values. Each panel corresponds to a specific even-oddness of the numbers of
nucleons in the parent nuclei in order to illustrate the role of the nuclear pairing. The solid
lines correspond to expression (2.4) with the two parameters $c_1$ and $c_2$ 4.59, 5.08 for panel
(a); 6.32, 6.34 for panel (b); 4.98, 5.53 for panel (c); 3.69, 4.80 for panel (d), respectively.}
\end{figure}
现在要将其读入变量strall中,方法如下:
filename='xxx.txt';
fid=fopen(filename,'r');
if fid<=0
fprintf('fail to open:%s!\n',filename);
return
end
i=1;strall='';
while ~feof(fid)
strall(i)=fscanf(fid,'%c',1);
i=i+1;
end
所得到的变量strall就是xxx.txt文档中的所有字符!
全部回答
  • 1楼网友:鸽屿
  • 2021-01-24 01:53
我这里有一个读取的实例你可以看一下 %% 格式化文本的读操作%只读形式打开txt文件file_t = fopen('mytxt.txt','r');%以十进制读取,且读取的数据自动排成一列,排的顺序为:先从第一行左边到第一行右边,然后排第二行a = fscanf(file_t,'%d');%关闭文件fclose(file_t);%% 使用textscan读取多列数据file_t = fopen('mytxt.txt','r');%将原来的两列数据以数组原包(cell)的形式读取,cell共有两个元素a = textscan(file_t,'%d %d');%c和上面a一样,d返回位置信息[c,d] = textscan(file_t,'%d %d');fclose(file_t);a{1} %原包数据的第一个元素对应第一列a{2}cd%% textread函数读取,现在不常用%这种形式将每一列分别给a,b[a,b] = textread('mytxt.txt','%d %d');ab%这种形式将txt文件排成一列赋给cc = textread('mytxt.txt','%d');c%% 忽略标题file_t = fopen('headline.txt','r');%忽略掉第一行的标题信息a = textscan(file_t,'%d %d','headerlines',1);a%% 使用textscan扫描字符串中的数据clcstr_1 = 'the number is 1 2 3 4 5';%首先使用textscan获取第一个前14个字符[str1,position1] = textscan(str_1,'%14c',1);str1{:}; %the number is position1; %14%获取字符串的长度[temp1,temp2] = size(str_1);%然后读取后面的数字字符串str_2 = textscan(str_1(position1+1:temp2),'%9c',1);%将字符串转化为数值num = str2num(str_2{1})%% 格式化文本的写操作%使用fprintf向文件中写入数据%写形式打开文件,存在就打开,不存在新创建一个文件开始写file_1 = fopen('text_w.txt','w');%以数字形式写入数据fprintf(file_1,'%d',1225);%关闭文件,返回0表示关闭成功fclose(file_1);%% 每写入一次换行或插入想要的字符file_1 = fopen('text_w.txt','w');%\r回车符 \n换行符 这里必须回车换行连用fprintf(file_1,'%d\r\n',[32;34]);%每写入一个数字,后加一个空格,多列按列输出temp = randint(4,2);fprintf(file_1,'%d ',temp);fclose(file_1);%% fprintf在命令空间输出str_1 = 'hello! world!';%这里fid = 1;这时输出换行只需\n就行,%c为输出单个字符,%s为输出字符串fprintf(1,'%c\n',str_1);%% 扫描字符串2clearclcstr = '1985 112 -10.53';%将 替换为0a = find(str == 32);str(a) = 48;%下面这这一句相当于+198501120-10.53%不是你给的+19850112-010.53str2num(str)
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯