Matlab - how to remove a line break when printing to screen? - matlab

There is for example a big big score
for 2 hours
and there is need to see how many more before the end of
do output on the screen of the outer loop
but the values ​​and there are many, such as 70 000
Question - how to remove a line break when printing to screen
not to receive 70 000 lines
and to see only the current display in one line?

Instead of using disp to display text to the screen, use fprintf, which requires you to enter line breaks manually.
Compare
>> disp('Hello, '), disp('World')
Hello,
World
with
>> fprintf('Hello, '), fprintf('World\n')
Hello, World
The \n at the end of 'World\n' signifies a line break (or newline as they're commonly called).

Try this function, which you can use in place of disp for a string argument. It displays to the command window, and remembers the message it has displayed. When you call it the next time, it first deletes the previous output from the command window (using ASCII backspace characters), then prints the new message.
In this way you only get to see the last message, and the command window doesn't fill up with old messages.
function teleprompt(s)
%TELEPROMPT prints to the command window, over-writing the last message
%
% TELEPROMPT(S)
% TELEPROMPT() % Terminate
%
% Input S is a string.
persistent lastMsg
if isempty(lastMsg)
lastMsg = '';
end
if nargin == 0
lastMsg = [];
fprintf('\n');
return
end
fprintf(repmat('\b', 1, numel(sprintf(lastMsg))));
fprintf(s);
lastMsg = s;

Related

string concatenation from a .txt file matlab

I am trying to concatenate three lines (I want to leave the lines as is; 3 rows) from Shakespeare.txt file that shows:
To be,
or not to be:
that is the question.
My code right now is
fid = fopen('Shakespeare.txt')
while ~feof(fid)
a = fgets(fid);
b = fgets(fid);
c = fgets(fid);
end
fprintf('%s', strcat(a, b, c))
I'm supposed to use strcat and again, I want concatenated and leave them as three rows.
One method of keeping the rows separate is by storing the lines of the text file in a string array. Here a 1 by 3 string array is used. It may also be a good idea to use fgetl() which grabs each line of the text file at a time. Concantenating the outputs of fgetl() as strings may also be another option to ensure the they do not get stored as character (char) arrays. Also using the \n indicates to line break when printing the strings within the array String_Array.
fid = fopen('Shakespeare.txt');
while ~feof(fid)
String_Array(1) = string(fgetl(fid));
String_Array(2) = string(fgetl(fid));
String_Array(3) = string(fgetl(fid));
end
fprintf('%s\n', String_Array);
Ran using MATLAB R2019b

How to search a text document by position

I need to search a text file that is about 30 lines. I need it to search row by row and grab numbers based on their position in the text file that will remain constant throughout the text file. Currently I need to get the first 2 numbers and then the last 4 numbers of each row. My code now:
FileToOpen = fopen(textfile.txt)
if FileToOpen == -1
disp('Error')
return;
end
while true
msg = fgetl(FileToOpen)
if msg == -1
break;
end
end
I would like to use the fgetl command if possible as I somewhat know that command, but if their is an easier way that will be more than welcome.
This looks like a good start. You should be able to use msg - '0' to get the value of the numbers. For ascii code the digits are placed next to each other in the right order (0,1,2,3,4,5,6,7,8,9). What you do when you subtract with '0' is that you subtract msg with the ascii code of '0'. You will then get the digits as
tmp = msg - '0';
idx = find(tmp>=0 & tmp < 10); % Get the position in the row
val = tmp(idx); % Or tmp(tmp>=0 & tmp < 10) with logical indexing.
I agree that fgetl is probably the best to use for text without specific structure. However, in case you have a special structure of the text you can use that and thus be able to use more effective algorithms.
In case you was actually after finding the absolute position of the digits in the text, you can save the msgLength = msgLength + length(msg) for every iteration and use that to calculate the absolute position of the digits.

Modify the value of a specific position in a text file in Matlab

AIR, ID
AIR.SIT
50 1 1 1 0 0 2 1
43.57 -116.24 1. 857.7
Hi, All,
I have a text file like above. Now in Matlab, I want to create 5000 text files, changing the number "2" (the specific number in the 3rd row) from 1 to 5000 in each file, while keeping other contents the same. In every loop, the changed number is the same with the loop number. And the output in every loop is saved into a new text file, with the name like AIR_LoopNumber.SIT.
I've spent some time writing on that. But it is kind of difficult for a newby. Here is what I have:
% - Read source file.
fid = fopen ('Air.SIT');
n = 1;
textline={};
while (~feof(fid))
textline(n,1)={fgetl(fid)};
end
FileName=Air;
% - Replace characters when relevant.
for i = 1 : 5000
filename = sprintf('%s_%d.SIT','filename',i);
end
Anybody can help on finishing the program?
Thanks,
James
If your file is so short you do not have to read it line by line. Just read the full thing in one variable, modify only the necessary part of it before each write, then write the full variable back in one go.
%% // read the full file as a long sequence of 'char'
fid = fopen ('Air.SIT');
fulltext = fread(fid,Inf,'char') ;
fclose(fid) ;
%% // add a few blank placeholder (3 exactly) to hold the 4 digits when we'll be counting 5000
fulltext = [fulltext(1:49) ; 32 ; 32 ; 32 ; fulltext(50:end) ] ;
idx2replace = 50:53 ; %// save the index of the characters which will be modified each loop
%% // Go for it
baseFileName = 'AIR_%d.SIT' ;
for iFile = 1:1000:5000
%// build filename
filename = sprintf(baseFileName,iFile);
%// modify the string to write
fulltext(idx2replace) = num2str(iFile,'%04d').' ; %//'
%// write the file
fidw = fopen( filename , 'w' ) ;
fwrite(fidw,fulltext) ;
fclose(fidw) ;
end
This example works with the text in your example, you may have to adjust slightly the indices of the characters to replace if your real case is different.
Also I set a step of 1000 for the loop to let you try and see if it works without writing 1000's of file. When you are satisfied with the result, remove the 1000 step in the for loop.
Edit:
The format specifier %04d I gave in the first solution insure the output will take 4 characters, and it will pad any smaller number with zero (ex: 23 => 0023). It is sometimes desirable to keep the length constant, and in your particular example it made things easier because the output string would be exactly the same length for all the files.
However it is not mandatory at all, if you do not want the loop number to be padded with zero, you can use the simple format %d. This will only use the required number of digits.
The side effect is that the output string will be of different length for different loop number, so we cannot use one string for all the iterations, we have to recreate a string at each iteration. So the simple modifications are as follow. Keep the first paragraph of the solution above as is, and replace the last 2 paragraphs with the following:
%% // prepare the block of text before and after the character to change
textBefore = fulltext(1:49) ;
textAfter = fulltext(51:end) ;
%% // Go for it
baseFileName = 'AIR_%d.SIT' ;
for iFile = 1:500:5000
%// build filename
filename = sprintf(baseFileName,iFile);
%// rebuild the string to write
fulltext = [textBefore ; num2str(iFile,'%d').' ; textAfter ]; %//'
%// write the file
fidw = fopen( filename , 'w' ) ;
fwrite(fidw,fulltext) ;
fclose(fidw) ;
end
Note:
The constant length of character for a number may not be important in the file, but it can be very useful for your file names to be named AIR_0001 ... AIR_0023 ... AIR_849 ... AIR_4357 etc ... because in a list they will appear properly ordered in any explorer windows.
If you want your files named with constant length numbers, the just use:
baseFileName = 'AIR_%04d.SIT' ;
instead of the current line.

How to get rid of the punctuation? and check the spelling error

eliminate punctuation
words split when meeting new line and space, then store in array
check the text file got error or not with the function of checkSpelling.m file
sum up the total number of error in that article
no suggestion is assumed to be no error, then return -1
sum of error>20, return 1
sum of error<=20, return -1
I would like to check spelling error of certain paragraph, I face the problem to get rid of the punctuation. It may have problem to the other reason, it return me the error as below:
My data2 file is :
checkSpelling.m
function suggestion = checkSpelling(word)
h = actxserver('word.application');
h.Document.Add;
correct = h.CheckSpelling(word);
if correct
suggestion = []; %return empty if spelled correctly
else
%If incorrect and there are suggestions, return them in a cell array
if h.GetSpellingSuggestions(word).count > 0
count = h.GetSpellingSuggestions(word).count;
for i = 1:count
suggestion{i} = h.GetSpellingSuggestions(word).Item(i).get('name');
end
else
%If incorrect but there are no suggestions, return this:
suggestion = 'no suggestion';
end
end
%Quit Word to release the server
h.Quit
f19.m
for i = 1:1
data2=fopen(strcat('DATA\PRE-PROCESS_DATA\F19\',int2str(i),'.txt'),'r')
CharData = fread(data2, '*char')'; %read text file and store data in CharData
fclose(data2);
word_punctuation=regexprep(CharData,'[`~!##$%^&*()-_=+[{]}\|;:\''<,>.?/','')
word_newLine = regexp(word_punctuation, '\n', 'split')
word = regexp(word_newLine, ' ', 'split')
[sizeData b] = size(word)
suggestion = cellfun(#checkSpelling, word, 'UniformOutput', 0)
A19(i)=sum(~cellfun(#isempty,suggestion))
feature19(A19(i)>=20)=1
feature19(A19(i)<20)=-1
end
Substitute your regexprep call to
word_punctuation=regexprep(CharData,'\W','\n');
Here \W finds all non-alphanumeric characters (inclulding spaces) that get substituted with the newline.
Then
word = regexp(word_punctuation, '\n', 'split');
As you can see you don't need to split by space (see above). But you can remove the empty cells:
word(cellfun(#isempty,word)) = [];
Everything worked for me. However I have to say that you checkSpelling function is very slow. At every call it has to create an ActiveX server object, add new document, and delete the object after check is done. Consider rewriting the function to accept cell array of strings.
UPDATE
The only problem I see is removing the quote ' character (I'm, don't, etc). You can temporary substitute them with underscore (yes, it's considered alphanumeric) or any sequence of unused characters. Or you can use list of all non-alphanumeric characters to be remove in square brackets instead of \W.
UPDATE 2
Another solution to the 1st UPDATE:
word_punctuation=regexprep(CharData,'[^A-Za-z0-9''_]','\n');

Skipping Lines in Matlab Code

I am trying to create a Matlab code that strips the header off of a text file and proceeds in the pattern of recording a line and skipping the next three lines.
I have figured out how to strip the header, but do not know how to code so that the program only records lines 1 (after the header is removed) 5,9, 13, etc.
Any recommendations?
I don't know how your data is formatted, so the actual code you use may differ, but this should give you the idea
file_lines = {};
fid = fopen(filename);
while 1
text_line = fgetl(fid);
%quit reading on an empty line
if ~ischar(text_line)
break
end
%keep the lines that 1 as the first value (this is what you wanted, right?)
data_line = str2num(text_line)
if(data_line(1,1) == 1)
file_lines{end+1} = data_line;
end
end
fclose(fid);