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

StackOverflow https://stackoverflow.com/questions/23213914

質問

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

役に立ちましたか?

解決

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

他のヒント

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'));
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top