How to import non-comma/tab separated ASCII numerical data and render into vector (in matlab)

心已入冬 提交于 2019-12-25 16:08:15

问题


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.

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.)


回答1:


Use textscan for that:

fid = fopen('100000.txt','r');
PiT = textscan(fid,'%c',Inf);
fclose(fid);

PiT is a cell array, so convert it to a vector of chars:

PiT = cell2mat(PiT(1));

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);

EDIT

Here is another solution, using fscanf, as textscan may not return a cell-type result.

Read the file with 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');

Function int32 may be replaced by other conversion functions (e.g. double).




回答2:


It can be done in one line.

When you modify your text file to just include the post-comma digits 14... you can use fscanf to get the vector you want.

pi = fscanf( fopen('pi.txt'), '%1d' );  fclose all

or without modifying the file:

pi = str2double( regexp( fscanf( fopen('pi.txt') ,'%1c'), '[0-9]', 'match'));


来源:https://stackoverflow.com/questions/23213914/how-to-import-non-comma-tab-separated-ascii-numerical-data-and-render-into-vecto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!