Matlab - array deserialization

I have a program that collects data from a sensor and saves it in a text file. data n text file is as follows:

  [1,2,3,4]
 [5,6,7,8]
 [9L, 10L, 11L, 12L]

how to de-serialize arrays to vectors in matlab?

note I have several arrays with float values, so the request also applies to reading floats.

+4
source share
2 answers

Unfortunately, I did not find a cleaner solution for this - the problem, of course, is in the brackets at the beginning and at the end of each line. Here is a solution that reads a file line by line and runs textscan on lines with parentheses cut out. Separate vectors are stored in cell :

 fid = fopen('data.txt', 'r'); data = {}; while 1 tline = fgetl(fid); if ~ischar(tline); break; end A = textscan(tline, '%f', 'Delimiter', ',', 'Whitespace', '[ ]L\b\t'); data{end+1} = A{1}; end fclose(fid); 

L is considered here as a separator. If this information is really important to you and you want to perform a uint64 listing, the above code will need to be changed.

Change Following H.Muster's comment, you can read the entire file in one pass as follows:

 fid = fopen('data.txt', 'r'); A = textscan(fid, '%f', 'Delimiter', ',', 'Whitespace', '[ ]L\b\t'); fclose(fid); 

Now A contains one column vector with all your data. Therefore, if you know the sizes of the vectors in each row, you can divide A into parts with the correct sizes. If not, and each vector may have a different size, you will have to go to the first solution.

+3
source

Just a small addition - as soon as you remove the "L", your data is valid matlab code. you can read it like:

 text_data = '[1,2,3,4]'; parsed_data = eval(text_data); 
+3
source

Source: https://habr.com/ru/post/1438826/


All Articles