2015-10-26 94 views
0

我一直在努力寻找一种方法来使用MATLAB将字符串转换为.txt文件中的整数。for循环字符串到整数

这里是什么我的文件看起来像一个例子:

genes total_muts 
A2M  1 
AARS  4 
AASS  6 
ABCA1 105 
ABCA3 71 
ABCA4 563 

这里是我使用的脚本:

genes_disease = dataset('file', 'genes_totalshuffle.txt', 'Delimiter', '\t'); 
gene = genes_disease.genes 
total_muts = genes_disease.total_muts 
a = 0 

fileID = fopen('genes_totalshuffled.txt', 'w') 
for k = 1:length(genes_disease) 
    total_muts1 = total_muts(k); 
    num_total_muts = str2num(total_muts1)  
    r = randi([a num_total_muts],1); 
    fprint(fileID, '%4f %4f\n', num_total_muts, r) 
end 
fclose(fileID) 

当我运行该脚本,我得到一个错误通知我randn的尺寸输入需要是数字。我认为我的问题在于totalmuts变量。这个变量打印字符串而不是整数。我以为我可以使用str2num(),但我似乎无法得到适当的工作。有什么建议么?

*编辑:包括我试图使用str2num。此外,我试图生成一个随机生成的数字,介于0和我的文件中列出的值之间。

+0

您的问题中有几件事我没有得到。注意:如果你的变量'var'等于字符串''1''(是吗?),那么你可以用'num2str(var)'把它变成一个整数。 –

+1

另外赋值(k:k)没用,只用(k)。 – Adriaan

+0

“我以为我可以使用'str2num()',但我似乎无法得到适当的工作” - 请添加您尝试使用此代码。 – Dan

回答

3

您可以使用randi产生0totalmuts之间的数字与

r = randi([0 totalmuts]); 

我不得不改变输入数据是一个CSV

genes,total_muts 
A2M,1 
AARS,4 
AASS,6 
ABCA1,105 
ABCA3,71 
ABCA4,563 

然后将代码

genes_disease = dataset('file', 'genes_totalshuffle.txt', 'Delimiter', ','); 
gene = genes_disease.genes 
total_muts = genes_disease.total_muts 
a = 0 

fileID = fopen('genes_totalshuffled.txt', 'w') 
for k = 1:length(genes_disease) 
    totalmuts = total_muts(k); 
    genename = gene(k); 
    r = randi([a totalmuts]); 
    fprintf(fileID, '%4f %4f\n', totalmuts, r) % consider %d or %3d 
end 
fclose(fileID) 

它对我很好,outp使用

1.000000 1.000000 
4.000000 0.000000 
6.000000 3.000000 
105.000000 47.000000 
71.000000 46.000000 
563.000000 400.000000 
+1

'rand(1)'在这种情况下是多余的。只需要调用'rand'。但是,OP需要**整数**,所以请使用'randi'。 – rayryeng

+0

啊原来的语法是有道理的。 '兰迪([0 totalmuts],1)' – Steve

+0

@Steve,是的!但是,当我尝试使用这个时,我得到一个错误:'大小和输入必须是数字'。我不知道如何解决这个问题。 – cosmictypist