在Matlab上的文本文件中添加新列 [英] Adding new columns to a text file on matlab

查看:673
本文介绍了在Matlab上的文本文件中添加新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Matlab的新手,我需要一些帮助.我想重复使用txt文件中的三列,并添加我创建的另外两列.

I'm new to matlab and I need some help. I want to re-use three columns from a txt file and add two extra ones created by me.

我的.txt文件是:

"Abel" 70 1.80 55 M
"Ana" 55 1.73 68 F
"Xavier" 65 1.82 61 M
"Rui" 80 1.79 23 M

这是我编写的代码:

[nome,peso,altura,idade,genero]=textread('imc.txt','%q%n%f%n%c')

for k=1:length(peso)

    imc(k)=peso(k)./(altura(k).^2)
end

for k=1:length(imc)

    if imc(k)>24.9
        imc_ok{k}='over'
    elseif imc(k)<18.5
        imc_ok{k}='under'
    else
        imc_ok{k}='ok'
    end
end

imc=imc';
imc_ok=(imc_ok)';

fid=fopen('imc.txt','wt');

for i=1:length(imc)
fprintf(fid,'%q,%n,%f,%f,%s',nome(i,1),peso(i,1),altura(i,1),imc(i,1),imc_ok{i})
   end
fclose(fid)

我想用nomepesoalturaimcimc_ok创建一个新的文本文件,我尝试搜索并用(i,1)替换{i},但是它没有不行.

I would like to create a new text file with nome, peso, altura, imc and imc_ok, I've tried searching and replacing (i,1) for {i} but it didn't work.

"Abel" 70 1.80 21.6 ok
"Ana" 55 1.73 18.3 under 
"Xavier" 65 1.82 19.6 ok 
"Rui" 80 1.79 23 24.9 over

推荐答案

导致fprintf失败的主要原因是格式说明符中的%n.在matlab中,请使用%d.

The major thing which was making the fprintf fail was your %n in the format specifier. In matlab use a %d instead.

用修改后的格式说明符稍微重写最后一个循环将产生所需的输出:

slightly rewriting your last loop with a modified format specifier will produce the desired output:

%% // write new file
fileout = 'imc_out.txt' ;
fid=fopen(fileout,'wt');
for i=1:length(imc)
    fprintf(fid,'%s %d %3.2f %3.1f %s\n',nome{i},peso(i),altura(i),imc(i),imc_ok{i}) ;
end
fclose(fid)

这篇关于在Matlab上的文本文件中添加新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆