I have a text file, but unfortunately its been poorly formatted, however i want to read the content of the text file into a a matrix, but I don't know how to do that.
When 开发者_如何学运维try to use fscanf
, textscan
, textread
and the rest it just copies everything into one cell, but i don't want it that way.
This how the content looks like: so i want to read only the decimals not the absolute figures. Can someone help me.
1 : 13.27 ; 3 : 20.68 ; 6 : 8.271 ; 7 : 3.308 ; 8 : 8.328 ;
9 : 6.655 ; 10 : 16.58 ; 11 : 9.925 ; 12 : 12.41 ; 13 : 4.135 ;
14 : 9.925 ; 15 : 11.58 ; 16 : 10.87 ; 17 : 1.654 ; 18 : 4.962 ;
19 : 6.655 ; 22 : 10.98 ; 23 : 24.25 ; 24 : 47.33 ; 25 : 11.6 ;
26 : 9.925 ; 27 : 5.809 ; 28 : 5.001 ; 29 : 6.617 ; 30 : 7.577 ;
31 : 9.155 ; 32 : 7.444 ; 33 : 28.58 ; 34 : 9.155 ; 35 : 35.83 ;
Just using textscan and ignoring the things you don't need, like the numbers and : gives you quite a simple solution:
fid = fopen('test.txt', 'rt');
data = textscan(fid, '%*u %*1s %f', 'Delimiter', ';');
fclose(fid);
Change test.txt to your filename. data is a cell with your doubles in it.
>> data{:}
ans =
13.2700
20.6800
8.2710
3.3080
8.3280
6.6550
16.5800
9.9250
12.4100
4.1350
9.9250
11.5800
10.8700
1.6540
4.9620
6.6550
10.9800
24.2500
47.3300
11.6000
9.9250
5.8090
5.0010
6.6170
7.5770
9.1550
7.4440
28.5800
9.1550
35.8300
I assume that the colon (:) seperates values in a row and the semicolon (;) is separating rows. With this assumption the following function should read your data into a MATLAB matrix
function dat = readData(filename)
% FUNCTION dat = readData(filename)
% Reads data from a nonstandard formatted file, filename
% INPUTS:
% filename: Full path to data file with the following format
% 1 : 2; 3 : 4
% where the : separates values in a row and ; separates rows
% open the file for reading
fid = fopen(filename);
ii=0; % row index
while ~feof(fid) % loop until we find the end of the file
str = fgetl(fid); % get a line of text
while 1
% split the string into its component parts
% assume that values are split with colon ":" and
% rows are identified with a
% semicolon ";".
%
% split at the first row using strtok
[rowStr rem]=strtok(str,';');
% split rowStr using colon
[str1,str2]=strtok(rowStr,':');
% get rid of the colon in str2
str2 = strrep(str2,':',' ');
str1 =strtrim(str1);
str2 =strtrim(str2);
% store data if we found any
if ~isempty(str1)&& ~ isempty(str2)
ii=ii+1; % increment row index
dat(ii,:) = [str2double(str1) str2double(str2)];
end
if isempty(rem), break; end
str = rem(2:end);
end
end
fclose(fid);
You can than use the functions round, floor, ceil to extract the 'decimal values'.
conceptually:
take the string.
Change : and ; with spaces and \n (return) with ;
Assign the string to a variable, the variable should become a matrix.
With a dual loop change the value of each elemnt with
var(i,j)=floor(var(i,j)) - var(i,j);
Here you are (If I didn't misunderstood you).
精彩评论