问题描述
我想将10万个pi数字导入matlab并将其作为矢量进行操作。我已经从复制并粘贴了这些数字并将其保存在文本文件中。我现在在导入这些数字并将它们渲染为矢量时遇到了很多麻烦。
I want to import 100,000 digits of pi into matlab and manipulate it as a vector. I've copied and pasted these digits from here and saved them in a text file. I'm now having a lot of trouble importing these digits and rendering them as a vector.
我发现函数计算matlab中的数字。然而,即便如此,我也无法将输出转换为矢量,然后我可以将其绘制成情节。 (另外,对于100,000个数字来说,它至少在我的计算机上很慢。)
I've found this function which calculates the digits within matlab. However, even with this I'm having trouble turning the output into a vector which I could then, for example, plot. (Plus it's rather slow for 100,000 digits, at least on my computer.)
推荐答案
使用 textscan
为此:
fid = fopen('100000.txt','r');
PiT = textscan(fid,'%c',Inf);
fclose(fid);
PiT
是一个单元格数组,所以转换它是一个字符向量:
PiT
is a cell array, so convert it to a vector of chars:
PiT = cell2mat(PiT(1));
现在,你想要一个int矢量,但你必须丢弃小数周期才能使用标准功能:
Now, you want a vector of int, but you have to discard the decimal period to use the standard function:
Pi = cell2mat(textscan(PiT([1,3:end]),'%1d', Inf));
注意:如果你删除(手动)句点,你可以一次性完成:
Note: if you delete (manually) the period, you can do that all in once:
fid = fopen('100000.txt','r');
Pi = cell2mat(textscan(fid,'%1d',Inf));
fclose(fid);
编辑
这是另一个解决方案,使用 fscanf
,因为 textscan
可能不会返回单元格类型的结果。
Here is another solution, using fscanf
, as textscan
may not return a cell-type result.
使用 fscanf
读取文件:
fid = fopen('100000.txt','r');
Pi = fscanf(fid,'%c');
fclose(fid);
然后只取数字并将字符串转换为数字:
Then take only the digits and convert the string as digits:
Pi = int32(Pi((Pi>='0')&(Pi<='9')))-int32('0');
函数 int32
可能被其他转换所取代函数(例如 double
)。
Function int32
may be replaced by other conversion functions (e.g. double
).
这篇关于如何导入非逗号/制表符分隔的ASCII数值数据并渲染成向量(在matlab中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!