MATLAB Answers

0

how to read a textfile that contain an array of text values into matrix

Yoav Weizman 님이 질문을 제출함. 16 Mar 2017
I have a textfile that contain tab delimited hexadecimal values and I would like to transfer the values into an array with each element will keep a value in the table (attached)

  댓글 수: 0

로그인 to comment.

태그

답변 수: 4

Massimo Zanetti 님의 답변 16 Mar 2017
Massimo Zanetti 님이 편집함. 16 Mar 2017

Here is it, you should know how many columns your data span (I guessed by reading your file they are 25):
%open file
fname = 'PowerUpRampSpeed_1.txt';
fileID = fopen(fname);
%read formatted data as strings of 2 characters
A = textscan(fileID,'%2c','Delimiter','\t');
%reshape the vector to matrix size
cols = 25;
A = reshape( hex2dec(char(A)) , cols , [])';
%close file
fclose(fname);
Now, A is your matrix read into Matlab.

  댓글 수: 0

로그인 to comment.


Jan 님의 답변 16 Mar 2017
Jan 님이 편집함. 16 Mar 2017

fname = 'file.txt';
fid = fopen(fname, 'r');
if fid == -1
error('Cannot open file for reading: %s', fname);
end
A = fscanf(fid, '%2x', [25, inf]).';
fclose(fid);
The conversion of hexadecimal number is much faster in fscanf/sscanf then by hex2dec.

  댓글 수: 0

로그인 to comment.


Yoav Weizman 님의 답변 20 Mar 2017
per isakson 님이 편집함. 2 Jun 2017

Thanks Jan and Massimo
I managed to find the following solution and it worked
array=reshape(textread('filename','%s'),200,32);
I was wondering if there is any reason to favor textscan or fscanf solutions?

  댓글 수: 3

textscan is more powerful, fscanf is faster. If you have a running textscan version and import some dozens of files only, spending 15 minute to create a faster fscanf version is most likely a waste of time - a pre-mature optimization.
Your solution leaves the values as text. Were you wanting a text array, or were you wanting a numeric array?
Oddly, at least on OS-X, textread() is not able to read files with the original name PowerUpRampSpeed_1µs.txt claiming they do not exist . I will be filing a bug report on that.

로그인 to comment.


Walter Roberson 님의 답변 2 Jun 2017

S = fileread('PowerUpRampSpeed_1µs.txt');
temp = regexp( regexp(S, '\r?\n', 'split'), '\W+', 'split');
output = vertcat(temp{:});
The result will be a 32 x 200 cell array of character vectors; hex values will not be converted to numeric.

  댓글 수: 0

로그인 to comment.



Translated by