I have a .txt file that contains a data like this:
0000000011111000
0000001110001110
0000011000011111
0001110000000001
0011000000000001
0011000000000001
0110000000000001
0100000000000001
1100000000000001
1100000000000001
1000000000000001
1100000000000010
1100000000000110
0100000000001100
0110000000011000
0011111111110000
0
//repeats like this
The 0 at the end is a label that describes the 16x16 matrix of 0's and 1's. As you can see it is actually a binary image of 0.
I need to load this file as a 16x16 matrix. I have tried importdata, textscanand fscanf but none worked for me.
The file continues in this format.
My initial tought was to use '' as a delimiter for importdata, but that did not worked.
Is there a way to achieve this?
This is one way to read the file (see here for some documentation):
fid=fopen(textfile);
dat = textscan(fid,'%s',-1); % <-- read into cell array of strings
fclose(fid);
dat=char(dat); % <-- concatenate the strings into one char array
dat = double(dat)- '0'; % <-- convert to numeric 0/1 (48 = '0'+0)
The last row will contain the number represented ("0") and superfluous stuff, you can delete with e.g. dat(end,:)=[];
Happy trails!
Edit: Although the posted answer works with the input text file and input method I used, for the OP the code requires modification (probably due to a difference in input format):
i = 1 : length (dat{1,1})
result(i,:) = double(char(dat{1,1}{i,1})) - '0';
end
Related
I am generating 2500 values in Matlab in format (time,heart_rate, resp_rate) by using below code
numberOfSeconds = 2500;
time = 1:numberOfSeconds;
newTime = transpose(time);
number0 = size(newTime, 1)
% generating heart rates
heart_rate = 50 +(70-50) * rand (numberOfSeconds,1);
intHeartRate = int64(heart_rate);
number1 = size(intHeartRate, 1)
% hist(heart_rate)
% generating resp rates
resp_rate = 50 +(70-50) * rand (numberOfSeconds,1);
intRespRate = int64(resp_rate);
number2 = size(intRespRate, 1)
% hist(heart_rate)
% joining time and sensor data
joinedStream = strcat(num2str(newTime),{','},num2str(intHeartRate),{','},num2str(intRespRate))
dlmwrite('/Users/amar/Desktop/geenrated/rate.txt', joinedStream,'delimiter','');
The data shown in the console is alright, but when I save this data to a .txt file, it contains extra spaces in beginning. Hence I am not able to parse the .txt file to generate input stream. Please help
Replace the last two lines of your code with the following. No need to use strcat if you want a CSV output file.
dlmwrite('/Users/amar/Desktop/geenrated/rate.txt', [newTime intHeartRate intRespRate]);
πβπ π πππ’π‘πππ π π’ππππ π‘ππ ππ¦ ππΎπ ππ π‘βπ π ππππππ π‘ πππ π¦ππ’π πππ π. πβππ πππ π€ππ ππ₯ππππππ π€βπ¦ π¦ππ’ πππ‘ π‘βπ π’πππ₯ππππ‘ππ ππ’π‘ππ’π‘.
The data written in the file is exactly what is shown in the console.
>> joinedStream(1) %The exact output will differ since 'rand' is used
ans =
cell
' 1,60,63'
num2str basically converts a matrix into a character array. Hence number of characters in its each row must be same. So for each column of the original matrix, the row with the maximum number of characters is set as a standard for all the rows with less characters and the deficiency is filled by spaces. Columns are separated by 2 spaces. Take a look at the following smaller example to understand:
>> num2str([44, 42314; 4, 1212421])
ans =
2Γ11 char array
'44 42314'
' 4 1212421'
I want to use fscanf for reading a text file containing 4 rows with an unknown number of columns. The newline is represented by two consecutive spaces.
It was suggested that I pass : as the sizeA parameter but it doesn't work.
How can I read in my data?
update: The file format is
String1 String2 String3
10 20 30
a b c
1 2 3
I have to fill 4 arrays, one for each row.
See if this will work for your application.
fid1=fopen('test.txt');
i=1;
check=0;
while check~=1
str=fscanf(fid1,'%s',1);
if strcmp(str,'')~=1;
string(i)={str};
end
i=i+1;
check=strcmp(str,'');
end
fclose(fid1);
X=reshape(string,[],4);
ar1=X(:,1)
ar2=X(:,2)
ar3=X(:,3)
ar4=X(:,4)
Once you have 'ar1','ar2','ar3','ar4' you can parse them however you want.
I have found a solution, i don't know if it is the only one but it works fine:
A=fscanf(fid,'%[^\n] *\n')
B=sscanf(A,'%c ')
Z=fscanf(fid,'%[^\n] *\n')
C=sscanf(Z,'%d')
....
You could use
rawText = getl(fid);
lines = regexp(thisLine,' ','split);
tokens = {};
for ix = 1:numel(lines)
tokens{end+1} = regexp(lines{ix},' ','split'};
end
This will give you a cell array of strings having the row and column shape or your original data.
To read an arbitrary line of text then break it up according the the formating information you have available. My example uses a single space character.
This uses regular expressions to define the separator. Regular expressions powerful but too complex to describe here. See the MATLAB help for regexp and regular expressions.
I have the following sample from a CSV file. Structure is:
Date ,Time(Hr:Min:S:mS), Value
2015:08:20,08:20:19:123 , 0.05234
2015:08:20,08:20:19:456 , 0.06234
I then would like to read this into a matrix in MATLAB.
Attempt :
Matrix = csvread('file_name.csv');
Also tried an attempt formatting the string.
fmt = %u:%u:%u %u:%u:%u:%u %f
Matrix = csvread('file_name.csv',fmt);
The problem is when the file is read the format is wrong and displays it differently.
Any help or advice given would be greatly appreciated!
EDIT
When using #Adriaan answer the result is
2015 -11 -9
8 -17 -1
So it seems that MATLAB thinks the '-' is the delimiter(separator)
Matrix = csvread('file_name.csv',1,0);
csread does not support a format specifier. Just enter the number of header rows (I took it to be one, as per example), and number of header columns, 0.
You file, however, contains non-numeric data. Thus import it with importdata:
data = importdata('file_name.csv')
This will get you a structure, data with two fields: data.data contains the numeric data, i.e. a vector containing your value. data.textdata is a cell containing the rest of the data, you need the first two column and extract the numerics from it, i.e.
for ii = 2:size(data.textdata,1)
tmp1 = data.textdata{ii,1};
Date(ii,1) = datenum(tmp1,'YYYY:MM:DD');
tmp2 = data.textdata{ii,2};
Date(ii,2) = datenum(tmp2,'HH:MM:SS:FFF');
end
Thanks to #Excaza it turns out milliseconds are supported.
I have a text file like below:
TestData
6.84 11.31 17.51 22.62 26.91 31.98 36.47 35.85 28.47 20.57 10.50 6.37 test1
0.24 2.62 4.94 7.17 10.39 15.37 18.73 18.29 12.26 6.46 1.15 -0.33 test2
68.47 95.04156.07218.39304.31320.22311.69269.22203.01135.60 68.18 55.09 test3
68.47 95.04156.07218.39304.31320.22311.69269.22203.01135.60 68.18 55.09 test4
...
As you can see, the first two lines are comments to ignore. In the following lines, there is a comment at the end of each line too. Each number is in the form of %6f. Also, there are blank lines in between.
I want to read in all the numbers into a matrix to make plots. I tried to use textscan, but had problems to ignore the last column, the blank lines and read in numbers that are connected (e.g., some numbers in the line: test4).
Here is the code I have by now:
data=dir('*.txt');
formatspecific='%6f%6f%6f%6f%6f%6f%6f%6f%6f%6f%6f%6f';
for i=1:length(data);
TestData1=data(i).name;
tempData=textscan(TestData1,formatspecific,'HeaderLines',2);
end
Anybody can help to make a sample code to improve the textscan part?
To use textscan to read a file, you have to "open" it before calling textscan and "close" it after; you should use
fopen to open the input file
fclose to close the input file
textscan returns a cellarray with the content read from the input file; since you are reading more than one file, you should change the way you manage the cellarray returned by textscan, actually, as it is now in your code, the data are overwritten at each iteration.
One possibility could be to store the data in an array of struct with, for example, 2 fields: the name of the input file and the data.
Another possibility could be to generate a struct whos each fields contains the data read from the input file; you can automatically generate the name of the fileds.
Another one possibility could be to store them into a a matrix.
Hereafter, you can find a script in which these three alternative have been implemented.
Code Updated (following the comment received)
In order to be able to correctly read data such as 95.04156.07 as 95.04 156.07, the format specifier should be modified from %6f to %6.2f
% Get the list of input data
data=dir('input_file*.txt');
% Define the number of data column
n_data_col=12;
% Define the number of heared lines
n_header=2;
% Build the format specifier string
% OLD format specifier
formatspecific=[repmat('%6f',1,n_data_col) '%s']
% NEW format specifier
formatspecific=[repmat('%6.2f',1,n_data_col) '%s']
% Initialize the m_data matrix (if you know in advance the numer of row of
% each input file yoiu can define since the beginning the size of the
% matrix)
m_data=[];
% Loop for input file reading
for i=1:length(data)
% Get the i-th file name
file_name=data(i).name
% Open the i-th input file
fp=fopen(file_name,'rt')
% Read the i-th input file
C=textscan(fp,formatspecific,'headerlines',n_header)
% Close the input file
fclose(fp)
% Assign the read data to the "the_data" array struct
the_data(i).f_name=file_name
the_data(i).data=[C{1:end-1}]
% Assign the data to a struct whos fileds are named after the inout file
data_struct.(file_name(1:end-4))=[C{1:end-1}]
% Assign the data to the matric "m_data
m_data=[m_data;[C{1:end-1}]]
end
Input file
TestData
6.84 11.31 17.51 22.62 26.91 31.98 36.47 35.85 28.47 20.57 10.50 6.37 test1
0.24 2.62 4.94 7.17 10.39 15.37 18.73 18.29 12.26 6.46 1.15 -0.33 test2
68.47 95.04156.07218.39304.31320.22311.69269.22203.01135.60 68.18 55.09 test3
68.47 95.04156.07218.39304.31320.22311.69269.22203.01135.60 68.18 55.09 test4
Output
m_data =
Columns 1 through 7
6.8400 11.3100 17.5100 22.6200 26.9100 31.9800 36.4700
0.2400 2.6200 4.9400 7.1700 10.3900 15.3700 18.7300
68.4700 95.0400 156.0700 218.3900 304.3100 320.2200 311.6900
68.4700 95.0400 156.0700 218.3900 304.3100 320.2200 311.6900
Columns 8 through 12
35.8500 28.4700 20.5700 10.5000 6.3700
18.2900 12.2600 6.4600 1.1500 -0.3300
269.2200 203.0100 135.6000 68.1800 55.0900
269.2200 203.0100 135.6000 68.1800 55.0900
Hope this helps.
I have a large text file (~3500 lines) which contains output data from an instrument. This consists of repeated entries from different measurements which are all formatted as follows:
* LogFrame Start *
variablename1: value
variablename2: value
...
variablename35: value
* LogFrame End *
Each logframe contains 35 variables. From these I would like to extract two, 'VName' and 'EMGMARKER' and put the associated values in columns in a matlab array, (i.e. the array should be (VName,EMGMARKER) which I can then associate with data from another output file which I already have in a matlab array. I have no idea where to start with this in order to extract the variables from this file, so hence my searches on the internet so far have been unsuccessful. Any advice on this would be much appreciated.
You could use textscan:
C = textscan(file_id,'%s %f');
Then you extract the variables of interest like this:
VName_indices = strcmp(C{1},'VName:');
VName = C{2}(VName_indices);
If the variable names, so 'VName' and 'EMGMARKER' , are always the same you can just read through the file and search for lines containing them and extract data from there. I don't know what values they contain so you might have to use cells instead of arrays when extracting them.
fileID = fopen([target_path fname]); % open .txt file
% read the first line of the specified .txt file
current_line = fgetl(fileID);
counter = 1;
% go through the whole file
while(ischar(current_line))
if ~isempty(strfind(current_line, VName))
% now you find the location of the white space delimiter between name and value
d_loc = strfind(current_line,char(9));% if it's tab separated - so \t
d_loc = strfind(current_line,' ');% if it's a simple white space
variable_name{counter} = strtok(current_line);% strtok returns everything up until the first white space
variable_value{counter} = str2double(strtok(current_line(d_loc(1):end)));% returns everything form first to second white space and converts it into a double
end
% same block for EMGMARKER
counter = counter+1;
current_line = fgetl(fileID);% next line
end
You do the same for EMGMARKER and you have cells containing the data you need.