Is default '\n' line terminator can be changed? - matlab

Is default '\n' Matlab line terminator can be changed? Can I use ',' instead of '\n'? Because the serial port that will be reading it is programmed to terminate when ',' is read.Is it possible?
Any answers are highly appreciated! Thanks in advance!

use eg:
ser = serial('COM1'); % establish connection between Matlab and COM1
set(ser, 'Terminator', 'CR'); % set communication string to end on ASCII 13
and replace 'CR' with ','
See
http://www.swarthmore.edu/NatSci/ceverba1/Class/e5/E5MatlabExamples.html
http://www.mathworks.co.uk/help/matlab/matlab_external/terminator.html

A simple string in matlab is not terminated by \n or \0 since it is a simple array of chars, as seen here:
>> a = string('Hello World')
Warning: string is obsolete and will be discontinued.
Use char instead.
a =
Hello World
>> double(a)
ans =
72 101 108 108 111 32 87 111 114 108 100
to add a \0 to the end simply use:
>> a(end+1)=0;
>> a
a =
Hello World
>> double(a) %the zero is there, but not printable as seen here
ans =
72 101 108 108 111 32 87 111 114 108 100 0

Related

Matlab: delete complete line in txt-file if there is a non-ascii-character

I'm currently writing a Matlab code to plot measurement data. Unfortunately there is a hardware problem with serial communication and sometimes i receive just gibberish. My code works only for defined data, so this gibberish has to be removed. I want something like this pseudo code:
for eachLine
if currentLineContainsNonASCII
delete completeLine
end if
end for
the data is read like this
rawdataInputFilename = 'measurementData.txt';
fileID = fopen(rawdataInputFilename);
% load data as string
DataCell = textscan(fileID,'%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s','HeaderLines', 1);
I was thinking about first creating a new 'clean' file with only ASCII chars and then reading that file with my actual plotting code.
Where I stuck is how to identify a non ASCII and then deleting the whole line, not only overwriting that single char.
Some example data, 1. and 3. line are 'clean' and can be handled with the current code. Second Line has non ASCIIs in it and therefore kills my code. Whitespace characters are windows linefeed, tab and space.
61 380 Module03 Slot02 27.01.2015 13:47:13 450 3587 1175 84 101.83 22.30 5.20 1 1
62 386 Module03 Slot03 27.01.2015 13:47:18 450ÆădzШШ 106.83 22.30 25.20 1 1
63 391 Module03 Slot04 27.01.2015 13:47:24 ERROR dgsf 5643332 103.26 22.40 25.20 1 1
You can just check if the received character is in the range [32, 127], otherwise skip it.
The following function will tell you if there is any non-printable character in a given string:
function R = has_non_printable_characters(str)
% Remove non-printable characters
str2 = str(31<str & str<127);
% check if length of resulting string is the same than input string
R = (lenght(str) > length(str2))
end;
If instead of just skipping the entire string you want to remove non-printable characters keeping the printable ones, modify the function and return str2. (And change the function name so it matches the new behaviour)
There are several ways to do it.
Save that to a text file named data.txt:
bla Header bla
61 380 Module03 Slot02 27.01.2015 13:47:13 450 3587 1175 84 101.83 22.30 5.20 1 1
62 386 Module03 Slot03 27.01.2015 13:47:18 450ÆădzШШ 106.83 22.30 25.20 1 1
63 391 Module03 Slot04 27.01.2015 13:47:24 ERROR dgsf 5643332 103.26 22.40 25.20 1 1
Method 1 (using textscan and cellfun):
Removing the non-ASCII line completely:
fileID = fopen('data.txt'); % open file
DataCell = textscan(fileID,'%s','delimiter','','HeaderLines', 1); % read a complete line of text, ignore the first line
fclose(fileID); % close file
DataCell = DataCell{1}; % there is only one string per line
DataCell(cellfun(#(x) any(x>127),DataCell)) = []; % remove line if there is any non-ASCII in it, adjust that to your liking, i.e (x>126 | x<32)
celldisp(DataCell)
DataCell{1} =
61 380 Module03 Slot02 27.01.2015 13:47:13 450 3587 1175 84 101.83 22.30 5.20 1 1
DataCell{2} =
63 391 Module03 Slot04 27.01.2015 13:47:24 ERROR dgsf 5643332 103.26 22.40 25.20 1 1
You could now loop over the cell array or, if you like, start all over again with the updated text (f.e. as input to textscan). To do that join the cells together to one big chunk of text:
strjoin(DataCell','\n')
ans =
61 380 Module03 Slot02 27.01.2015 13:47:13 450 3587 1175 84 101.83 22.30 5.20 1 1
63 391 Module03 Slot04 27.01.2015 13:47:24 ERROR dgsf 5643332 103.26 22.40 25.20 1 1
Method 2 (using regexprep):
I'm loading the whole text file at once and replacing any line with an empty string '', which does not contain a given set of characters.
s = fileread('data.txt');
snew = regexprep(s, '.*[^\w\s.:].*\n', '', 'dotexceptnewline')
snew =
61 380 Module03 Slot02 27.01.2015 13:47:13 450 3587 1175 84 101.83 22.30 5.20 1 1
63 391 Module03 Slot04 27.01.2015 13:47:24 ERROR dgsf 5643332 103.26 22.40 25.20 1 1
The [^\w\s.:] bit bascially translates to:
Match any chararcter which is not (the ^ means not):
alphabetic, numeric or underscore (\w)
whitespace (\s)
a dot . or
a colon :
If you want to exclude any other ASCII character, just add it (to within the brackets).
here is the code which creates a new txt-file whitout the lines with non-ASCII
%% read in via GUI
[inputFilename, inputPathname] = uigetfile('*.txt', ...
'Pick a .txt file from which you want to remove lines with non ASCII characters.');
if isequal(inputFilename, 0)
disp('User selected ''Cancel''')
else
disp(['User selected ', fullfile(inputPathname, inputFilename)])
inputFileID = fopen(fullfile(inputPathname, inputFilename)); %open/load file
end
tempCell = (strsplit(inputFilename,'.'));
inputFilenameWOextension = cell2mat(tempCell(1));
fileExtension = cell2mat(tempCell(2));
outputFileID = fopen([inputFilenameWOextension, '_ASCIIonly.', fileExtension], 'w'); %overwrite existing file
% get a single line of text
tline = fgetl(inputFileID);
while tline ~= -1
% get a single line of text
tline = fgetl(inputFileID);
% Remove non-printable characters
tempStr = tline(tline<127); % not really ASCII, but also tab
%tempStr = tline(31<tline & tline<127); % true ASCII
if (length(tempStr) < length(tline));
continue;
else
fprintf(outputFileID, '%s\r\n', tempStr);
end
end
fclose(inputFileID);
fclose(outputFileID);

Concatenation of Matlab strings

I want to make a Matlab function that takes two matrices A and B (of the same size) and combines them in a certain way to give an output that can be used in Latex - table.
I want the first row of the output matrix to consist of the first row of matrix A, with ampersands (&) in between them, and that ends with an double backslash.
The second row should be the first row of B with parentheses around them, and ampersands in between. And so on for the rest of A and B.
If I let A=rand(1,2), I could do this by using [num2str(A(1)), ' & ', num2str(A(2)),' \\'] and so on.
But I want to be able to make a function that does this for any size of the matrix A. I guess I have to make cell structures in some way. But how?
This could be one approach -
%// First off, make the "mixed" matrix of A and B
AB = zeros(size(A,1)*2,size(A,2));
AB(1:2:end) = A;
AB(2:2:end) = B;
%// Convert all numbers of AB to characters with ampersands separating them
AB_amp_backslash = num2str(AB,'%1d & ');
%// Remove the ending ampersands
AB_amp_backslash(:,end-1:end) = [];
%// Append the string ` \\` and make a cell array for the final output
ABcat_char = strcat(AB_amp_backslash,' \\');
ABcat_cell = cellstr(ABcat_char)
Sample run -
A =
183 163 116 50
161 77 107 91
150 124 56 46
B =
161 108 198 4
198 18 14 137
6 161 188 157
ABcat_cell =
'183 & 163 & 116 & 50 \\'
'161 & 108 & 198 & 4 \\'
'161 & 77 & 107 & 91 \\'
'198 & 18 & 14 & 137 \\'
'150 & 124 & 56 & 46 \\'
' 6 & 161 & 188 & 157 \\'
You can use sprintf, it will repeat the format spec as many times as required until all input variables are processed:
%combine both to one matrix
C=nan(size(A).*[2,1]);
C(1:2:end)=A;
C(2:2:end)=B;
%print
sprintf('%f & %f \\\\\n',C.')
The transpose (.') is required to fix the ordering.

In Matlab, with an English text file, how to load the file and get a matrix as an ASCII encoding result?

Firstly it is a very simple example:
In a text file ('test1.txt'), the content is:
Formally, the
What I want to get is an array with the ASCII encoding result like:
dat_ascii = [70 111 114 109 97 108 108 121 44 32 116 104 101]
In the result, every char is translated to ASCII code, even space and common.
Now I have a text file like 10MB full with English text. I want to read it and translate every char to ASCII code and put them into a matrix (with every 4096 char per line, many lines).
How can I do this in Matlab?
You can easily convert every thing in ASCII with :
double, you just cast to double your string.
And to revert it, just do char
Example :
myStr = 'I have 2 apple.'
myStr =
I have 2 apple.
myASCII = double(myStr)
myASCII =
73 32 104 97 118 101 32 50 32 97 112 112 108 101 46
myChar = char(myASCII)
myChar =
I have 2 apple.
In order to read text file in MATLAB, you need to open the text file and read
>> filePtr = fopen('test1.txt')
and then use the file pointer to read the data and convert to ASCII values:
>> ASCIIValues = double(textscan(filePtr, '%c')); ASCIIValues{:}
Note: Use the appropriate formatting argument when you try to read a text file. In my case, I neglect all whitespaces. For documentation, read http://www.mathworks.com/help/matlab/ref/textscan.html

matlab get the value of char

from MATLAB command line , when I type my variable a , it gives me values as expected :
a =
value_1
value_2
and I would like to access to each value of a, I tried a(1) but this gives me empty
the type of a is 1x49char.
how could I get value_1 and value_2 ?
whos('a')
Name Size Bytes Class Attributes
a 1x49 98 char
I get the a from xml file :
<flag ="value">
<flow>toto</flow>
<flow>titi</flow>
</flag>
a+0:
ans =
10 32 32 32 32 32 32 32 32 32 32 32 32 98,...
111 111 108 101 97 110 95 84 10 32 32 32 32 32,...
32 32 32 32 32 32 32 66 79 79 76 10 32 32,...
32 32 32 32 32 32 32
Perhaps a is a string with a newline in it. To make two separate variables, try:
values = strtrim(strread(a, '%s', 'delimiter', sprintf('\n')))
strread will split a into separate lines, and strtrim will remove leading/trailing whitespace.
Then you can access the lines using
values{1}
values{2}
(note that you must use curly brackets since this is a cell array of strings).
How are you reading in the xml file? If you're using xmlread then MatLab adds a lot of white space in there for you and could be the cause of your problems.
http://www.mathworks.com/matlabcentral/fileexchange/28518-xml2struct
This will put your xml file into a struct where you should be able to access the elements in the array.
You seem to have an somewhat inconvenient character array. You can convert this array in a more manageable form by doing something like what #Richante said:
strings = strread(a, '%s', 'delimiter', sprintf('\n'));
Then you can reference to toto and titi by
>> b = strings{2}
b =
toto
>> c = strings{3}
c =
titi
Note that strings{1} is empty, since a starts with a newline character. Note also that you don't need a strtrim -- that is taken care of by strread already. You can circumvent the initial newlines by doing
strings = strread(a(2:end), '%s', 'delimiter', sprintf('\n'));
but I'd only do that if the first newline is consistently there for all cases. I'd much rather do
strings = strread(a, '%s', 'delimiter', sprintf('\n'));
strings = strings(~cellfun('isempty', strings))
Finally, if you'd rather use textscan instead of strread, you need to do 1 extra step:
strings = textscan(a, '%s', 'delimiter', sprintf('\n'));
strings = [strings{1}(2:end)];

Agilent Vee or Matlab: 4 byte ASCII to floating point

I currently have an instrument that sends 4 bytes representing a floating point number of 32-bit in little endian format, the data looks like:
Gz*=
<«�=
N×e=
or this
à|ƒ=
is there a conversion for this in matlab, Agilent vee and manually
To convert an array of char to single, you can use typecast:
c = 'Gz*=';
f = typecast(c, 'single')
f = 0.041621
Just implicitly!
>> data = ['Gz*=';'<«�=';'N×e=']
data =
Gz*=
<«�=
N×e=
>> data+0
ans =
71 122 42 61
60 171 65533 61
78 215 101 61
data+0 forces it to be interpreted as a number which is fine.
If it's interpreted it backwards (I'm not sure if MATLAB is big or little endian) just use the swapbytes function.