How to read a single character in file using MATLAB? - matlab

In my file data.txt, I have a string abcdefgh. Now I want to take just 1 character without read whole string. How can I do this in MATLAB?
For example, I want to take the first character, I use c = fscanf(data.txt, '%c'); and c = textscan(data.txt, '%c'); but it read whole line in data.txt. I know that c(1) is my answer but I don't want to do that.

You can limit the number of characters that are read in using the third input to either fscanf or textscan.
fid = fopen('data.txt', 'r');
c = fscanf(fid, '%c', 1);
c = textscan(fid, '%c', 1);
You could also just use a lower-level function such as fread to do this.
fid = fopen('data.txt', 'r');
c = fread(fid, 1, '*char');

Related

Issue with format specification while reading from file Matlab

I have a .dat file with a table containing data in following order:
0,000E+0 4,069E-2 -5,954E+0 1,851E-2
What I need to do is to read this data with matlab and then somehow handle it.
Here is my code:
path = 'C:/Users/user/Desktop/file1.dat';
fileID = fopen(path,'r');
formatSpec = '%e';
A = fscanf(fileID,formatSpec);
fclose(fileID);
disp(A);
Unfortunately, it doesn't work. What did I do wrong?
After replacement of comma with dot in data you can read it using dlmread function:
M = dlmread('filename', ' ');
M is what you want.
For the first part, replacing a character, you can use the following code:
% read the file
fid = fopen('input.txt','r');
f=fread(fid,'*char')';
fclose(fid);
%replace the char
f = strrep(f,',','.');
% write into the another file
fid = fopen('output.txt','w');
fprintf(fid,'%s',f);
fclose(fid);

Appending data to a file in Matlab, removing before a symbol

I have a file which is written via Matlab from a vector M with binary data values. This file is written with Matlab's fwrite in the following script myGenFile.m of the form function myGenFile(fName, M):
% open output file
fId = fopen(fName, 'W');
% start by writing some things to the file
fprintf(fId, '{DATA BITLENGTH:%d}', length(M));
fprintf(fId, '{DATA LIST-%d:#', ceil(length(M) / 8) + 1);
% pad to full bytes
lenRest = mod(length(M), 8);
M = [M, zeros(1, 8 - lenRest)];
% reverse order in bytes
M = reshape(M, 8, ceil(length(M) / 8));
MReversed = zeros(8, ceil(length(M) / 8));
for i = 1:8
MReversed(i,:) = M(9-i,:);
end
MM = reshape(MReversed, 1, 8*len8);
fwrite(fId, MM, 'ubit1');
% write some ending of the file
fprintf(fId, '}');
fclose(fId);
Now I want to write a file myAppendFile.m, which appends some values to the existing file and has the following form: function myAppendFile(newData, fName). To do this I will have to remove the trailing '}':
fId = fopen(nameFile,'r');
oldData = textscan(fId, '%s', 'Delimiter', '\n');
% remove the last character of the file; aka the ending '}'
oldData{end}{end} = oldData{end}{end}(1:end-1);
The problem is now when trying to write oldData into the file (writing newData should be trivial, since it is also a vector of binary data like M), since it is a cell of cell arrays, containing strings.
How could I overcome this issue and append the new data correctly?
Instead of using textscan which copies the file to your memory, then writes it back, you could use fseek to set the pointer where you want to continue writing. Just put it one char before end of file and continue writing.
fseek(fid, -1, 'eof');

Matlab - string containing a number and equal sign

I have a data file that contains parameter names and values with an equal sign in between them. It's like this:
A = 1234
B = 1353.335
C =
D = 1
There is always one space before and after the equal sign. The problem is some variables don't have values assigned to them like "C" above and I need to weed them out.
I want to read the data file (text) into a cell and just remove the lines with those invalid statements or just create a new data file without them.
Whichever is easier, but I will eventually read the file into a cell with textscan command.
The values (numbers) will be treated as double precision.
Please, help.
Thank you,
Eric
Try this:
fid = fopen('file.txt'); %// open file
x = textscan(fid, '%s', 'delimiter', '\n'); %// or '\r'. Read each line into a cell
fclose(fid); %// close file
x = x{1}; %// each cell of x contains a line of the file
ind = ~cellfun(#isempty, regexp(x, '=\s[\d\.]+$')); %// desired lines: space, numbers, end
x = x(ind); %// keep only those lines
If you just want to get the variables, and reject lines that do not have any character, this might work (the data.txt is just a txt generated by the example of data you have given):
fid = fopen('data.txt');
tline = fgets(fid);
while ischar(tline)
tmp = cell2mat(regexp(tline,'\=(.*)','match'));
b=str2double(tmp(2:end));
if ~isnan(b)
disp(b)
end
tline = fgets(fid);
end
fclose(fid);
I am reading the txt file line by line, and using general expressions to get rid of useless chars, and then converting to double the value read.

How to use fscanf to detect line breaks?

I am using fscanf to import data into MATLAB. My text file is formatted as such:
######-10-K-########
######-10-K-########
The first number can vary anywhere from 6-9 characters. Right now I am using the code:
var = fcanf(fn, %s)
which is resulting in var being equal to one giant string.
I read that using %s will go on until it detects a whitespace. Is there anyone to get it to stop when it detects a linebreak instead?
Matlab has many functions, you can use textscan for example. Note that using textscan as follows trims all spaces in each line.
f = fopen('your_file_name');
file_data = textscan(f, '%s', 'Delimiter', '');
fclose(f);
Another example with fgetl as follows. fgetl keeps indents and spaces in each line.
lineCt = 1;
f = fopen('your_file_name');
tline = fgetl(f);
while ischar(tline)
f_data{lineCt} = tline;
lineCt = lineCt + 1;
tline = fgetl(f);
end
fclose(f);
Note that it should be fscanf instead of fcanf as you wrote.

Modifying PDF file with Matlab by fopen

Is it possible to use matlab to fopen a PDF file, manually replace a string ('Helvetica') with a new string ('Arial')? Probably due to the fact that the file is part binary and part ascii, if I
fid = fopen(filename, 'r');
str = fread(fid, '*char')';
fclose(fid);
newStr = strrep(str, 'Helvetica', 'Arial');
fid = fopen(filename, 'w');
fprintf(fid, '%s', newStr);
fclose(fid);
The PDF will be unusable at all. Is there a way to avoid this?
PS: 1) The PDF file may have very different sizes, so skipping a certain amount of binary data may be difficult;
2) I know how to do it in python, but I'd really like to see whether it could be done by pure MATLAB...
Thanks!
One way of doing this is to read the pdf as uint8 instead of char and write out with fwrite
fid = fopen(filename, 'r');
bytes = fread(fid, 'uint8')';
fclose(fid);
% Do the replacement
% NB: strrep complains about the byte array but works anyway
% You could do replacement without using string function
% but this works.
output = strrep(bytes,'Helvetica','Arial');
% Write out the modified pdf
fid = fopen(filename, 'w');
fwrite(fid, output);
fclose(fid);