当前位置:网站首页>Matlab learning notes (5) import and export of MATLAB data

Matlab learning notes (5) import and export of MATLAB data

2022-06-22 02:11:00 Linest-5

Catalog

MATLAB Data import

Example 1

Example 2

Example 3

MATLAB Low level files I / O

MATLAB Import text data files and low-level I/O

Specific examples

MATLAB Export data

Detailed examples

Write to journal file

MATLAB Low level I/O Data export to text data file

Detailed examples


MATLAB Data import

When writing a program , It's often necessary to read in data from the outside .MATLAB Open data in multiple formats . In this paper, MATLAB Import of data in .

MATLAB There are two ways to import data in :

  • Import data from the command line through code
  • adopt MATLAB Data Import Wizard to import data

This section describes the first data import method .

MATLAB Importing data in means loading data from an external file .importdata Function allows you to load files in different formats of various data . It has the following five forms :

S.N. function & explain
1

A = importdata(filename)

Load data from the file represented by the file name into the array A in .

2

A = importdata('-pastespecial') 

Load data from the system clipboard , Instead of loading data from a file .

3

A = importdata(___, delimiterIn) 

take delimiterIn Interpreted as ASCII file 、 Column separator in file name or clipboard data . Can be delimiterIn Use with any of the input parameters in the above syntax .

4

A = importdata(___, delimiterIn, headerlinesIn)

from ASCII file 、 File name or clipboard load data , And from lineheaderlinesIn+1 Start reading digital data .

5

[A, delimiterOut, headerlinesOut] = importdata(___)

Returns the detected separator character in the separator output , And use any of the input parameters in the previous syntax to detect headerlinesOut Number of header rows detected in .

Example 1

In this example, we will load and display the image file .

stay MATLAB Create a script file in , And enter the following code :

filename = 'ae86.jpg';
A = importdata(filename);
image(A);

Run the file ,MATLAB Display image file .

Be careful : The image file must be saved in the current directory , Otherwise, an error will be reported .

Example 2

In this case , We are MATLAB Import text file in , And specify the separator and column title .

We create spaces delimited ASCII Column header of the file , The file named weeklydata.txt.

text file weeklydata.txt The contents are as follows :

SunDay  MonDay  TuesDay  WednesDay  ThursDay  FriDay  SatureDay
95.01   76.21   61.54    40.57       55.79    70.28   81.53
73.11   45.65   79.19    93.55       75.29    69.87   74.68
60.68   41.85   92.18    91.69       81.32    90.38   74.51
48.60   82.14   73.82    41.03       0.99     67.22   93.18
89.13   44.47   57.63    89.36       13.89    19.88   46.60

stay MATLAB Create a script file in , And enter the following code :

filename = 'weeklydata.txt';
delimiterIn = ' ';            % The separator is an empty line  
headerlinesIn = 1;            % The non data part is the first line 
A = importdata(filename,delimiterIn,headerlinesIn);
% View data
for k = [1:7]                 %for sentence 
   disp(A.colheaders{1, k})   % Column header is k The name of the first row of the column 
   disp(A.data(:, k))         % The next step is k All data parts of the column 
   disp(' ')                  % One line apart 
end

Additional explanation :

disp The function outputs the contents in parentheses directly to the Matlab In the command window

For example, input command function :

disp(‘HELLO MATLAB!’)

Matlab The command window will output :

HELLO MATLAB!

Run the command , The following results are displayed :

SunDay
   95.0100
   73.1100
   60.6800
   48.6000
   89.1300
 
MonDay
   76.2100
   45.6500
   41.8500
   82.1400
   44.4700
 
TuesDay
   61.5400
   79.1900
   92.1800
   73.8200
   57.6300

WednesDay
   40.5700
   93.5500
   91.6900
   41.0300
   89.3600
 
ThursDay
   55.7900
   75.2900
   81.3200
    0.9900
   13.8900
 
FriDay
   70.2800
   69.8700
   90.3800
   67.2200
   19.8800

SatureDay
   81.5300
   74.6800
   74.5100
   93.1800
   46.6000

Example 3

This example shows how to import data from the clipboard to MATLAB.

Copy the following lines to the clipboard :

HELLO MATLAB

stay MATLAB Create a script file in , And enter the following code :

A = importdata('-pastespecial')

Run the file , The following results are displayed :

A = 
    'HELLO MATLAB'

MATLAB Low level files I / O

MATLAB in importdata  Function is a high-level function . If you want to deal with low-level files , stay MATLAB Medium I / O The function allows you to read or write data to a file with most control rights . however , The requirement of using these functions is that these files need to have more detailed information , This can improve work efficiency .

MATLAB Read and write operations of bytes or characters provide the following functions :

function describe
fclose Close one or all open files
feof End of test file
ferror Relevant documents I / O Wrong message
fgetl Read lines from file , Remove line breaks
fgets Read lines from file , Keep line breaks
fopen Open file , Or get information about open files
fprintf Write data to a text file
fread Read data from binary files
frewind Move the file location indicator to the beginning of the open file
fscanf Read data from a text file
fseek Move to the specified location in the file
ftell Get the location of the open file
fwrite Write data to binary file

MATLAB Import text data files and low-level I/O

MATLAB The low-level import text data file is implemented by the following function :

  • fscanf Function to read text or ASCII File format data .

  • fgetl Functions and fgets Function to read a one line file , The newline character separates each line .

  • fread The level of bytes or bits of the data stream read by the .

Specific examples

We have myfile.txt Text data files are stored in our working directory . The file is stored 3 Monthly rainfall data , Namely 2012 Year of 6 month ,7 The month and 8 month .

myfile.txt Contains the time of the duplicate dataset , There are five data items for a month's rainfall measurement . Header data is stored for several months , So we have M Group measurement .

The contents of the document are as follows :

Rainfall Data
Months: June, July, August
 
M=3
12:00:00
June-2012
17.21  28.52  39.78  16.55 23.67
19.15  0.35   17.57  NaN   12.01
17.92  28.49  17.40  17.06 11.09
9.59   9.33   NaN    0.31  0.23 
10.46  13.17  NaN    14.89 19.33
20.97  19.50  17.65  14.45 14.00
18.23  10.34  17.95  16.46 19.34
09:10:02
July-2012
12.76  16.94  14.38  11.86 16.89
20.46  23.17  NaN    24.89 19.33
30.97  49.50  47.65  24.45 34.00
18.23  30.34  27.95  16.46 19.34
30.46  33.17  NaN    34.89  29.33
30.97  49.50  47.65  24.45 34.00
28.67  30.34  27.95  36.46 29.34
15:03:40
August-2012
17.09  16.55  19.59  17.25 19.22
17.54  11.45  13.48  22.55 24.01
NaN    21.19  25.85  25.05 27.21
26.79  24.98  12.23  16.99 18.67
17.54  11.45  13.48  22.55 24.01
NaN    21.19  25.85  25.05 27.21
26.79  24.98  12.23  16.99 18.67

We import the data into this file , And display these data . Steps are as follows :

  1. Use fopen Function to open a file and get the file identifier .

  2. Describes the data format specifier in the file , Such as '%s' For a string ,'%d' It's an integer , or '%f' Represents a floating point number .

  3. Files to skip text characters , Include their format descriptions . To skip a data field , Use an asterisk in the symbol (“*”). for example , To read the header , And return a single M value , We write like this :

    M = fscanf(fid, '%*s %*s %*s %*s %*s %*s M=%d', 1);
  4. By default ,fscanf Reading data , Until it can be described according to our format that the data does not match , Or it reaches the end of the file . ad locum , We will use for Cycle through 3 Group data , every time , It reads 7 That's ok 5 Column .

  5. We will create a new one called mydata  In the workspace , Read the data storage structure from the file . This structure has three fields : Time 、 The month and raindata array .

stay MATLAB Create a script file in , And enter the following code :

filename = '/data/myfile.txt';
rows = 7;
cols = 5;
 
%  Open file 
fid = fopen(filename);
 
%  Read the file , obtain M Value 
M = fscanf(fid, '%*s %*s
%*s %*s %*s %*s
M=%d

', 1);
 
%  Read each set of measured values 
for n = 1:M
    mydata(n).time = fscanf(fid, '%s', 1);
    mydata(n).month = fscanf(fid, '%s', 1);
 
    % fscanf Fill the array in column order , Transpose result 
    mydata(n).raindata  = ...
      fscanf(fid, '%f', [rows, cols]);
end
for n = 1:M
    disp(mydata(n).time), disp(mydata(n).month)
    disp(mydata(n).raindata)
end
 
%  Close file 
fclose(fid);

Run the file , The following results are displayed :

12:00:00
June-2012
   17.2100   17.5700   11.0900   13.1700   14.4500
   28.5200       NaN    9.5900       NaN   14.0000
   39.7800   12.0100    9.3300   14.8900   18.2300
   16.5500   17.9200       NaN   19.3300   10.3400
   23.6700   28.4900    0.3100   20.9700   17.9500
   19.1500   17.4000    0.2300   19.5000   16.4600
    0.3500   17.0600   10.4600   17.6500   19.3400

09:10:02
July-2012
   12.7600       NaN   34.0000   33.1700   24.4500
   16.9400   24.8900   18.2300       NaN   34.0000
   14.3800   19.3300   30.3400   34.8900   28.6700
   11.8600   30.9700   27.9500   29.3300   30.3400
   16.8900   49.5000   16.4600   30.9700   27.9500
   20.4600   47.6500   19.3400   49.5000   36.4600
   23.1700   24.4500   30.4600   47.6500   29.3400

15:03:40
August-2012
   17.0900   13.4800   27.2100   11.4500   25.0500
   16.5500   22.5500   26.7900   13.4800   27.2100
   19.5900   24.0100   24.9800   22.5500   26.7900
   17.2500       NaN   12.2300   24.0100   24.9800
   19.2200   21.1900   16.9900       NaN   12.2300
   17.5400   25.8500   18.6700   21.1900   16.9900
   11.4500   25.0500   17.5400   25.8500   18.6700

MATLAB Export data

MATLAB Allow data to be read in another application ASCII file ,MATLAB Provides a variety of data output options .

You can create the following types of files :

  • rectangular , Separated from an array ASCII Data files .
  • Key and text output of journal or log file .
  • Professional ASCII file , Such as fprintf Use low-level functions .
  • Use MEX File to access your C/ C++ or Fortran The program writes to a specific text file format .

in addition , You can also export data to Excel.

Export numeric array as separator ASCII There are two methods of data file :

  • Use  save Function and the specified ASCII qualifiers
  • Use dlmwrite function

Use save The syntax of the function is as follows :

save my_data.out num_array -ASCII

among ,my_data.out Delimit ASCII Created data file ,num_array Is an array of numbers and ASCII operator .

dlmwrite The syntax of the function is as follows :

dlmwrite('my_data.out', num_array, 'dlm_char')

among ,my_data.out Delimit ASCII Created data file ,num_array Is a digital array and dlm_char As a separator .

Detailed examples

stay MATLAB Create a script file in , And enter the following code :

num_array = [ 1 2 3 4 ; 4 5 6 7; 7 8 9 0];
save array_data1.out num_array -ASCII;
type array_data1.out
dlmwrite('array_data2.out', num_array, ' ');
type array_data2.out

Run the file , The following results are displayed :

   1.0000000e+00   2.0000000e+00   3.0000000e+00   4.0000000e+00
   4.0000000e+00   5.0000000e+00   6.0000000e+00   7.0000000e+00
   7.0000000e+00   8.0000000e+00   9.0000000e+00   0.0000000e+00

1 2 3 4
4 5 6 7
7 8 9 0

Please note that save ASCII Command and dlmwrite Command as input does not work as a cell array .

To create a separate ASCII file , You can take the contents of an array of cells

  • or , Convert the cell array to a matrix using cell2mat function ,

  • Or export the cell array , Use low-level files I/O function .

If you use SAVE Function to write a character array ASCII file , It is equivalent ASCII Code characters are written to the file .

for example , Let the words written 'hello' The file of :

h = 'hello';
save textdata.out h -ascii
type textdata.out

MATLAB Execute the above statement , The following results are displayed :

1.0400000e+02   1.0100000e+02   1.0800000e+02   1.0800000e+02   1.1100000e+02

This is a string of characters 'hello' Of 8 position ASCII Format .

Write to journal file

Activity log of journal file MATLAB Conversation . The journal function creates an exact copy of your session file on disk , Excluding graphics .

Journal function to be opened , Input :

diary

perhaps , You can give the name of the log file , say :

diary logdata.out

Journal function to close :

diary off

You can open the journal file in a text editor .

MATLAB Low level I/O Data export to text data file

up to now , We have exported the digital array .MATLAB Provide low-level fprintf Function to create other text files , Including combined numeric and character data , Non rectangular output file , Or use non ASCII coding scheme .

At a low level I/O Document activity , You need to use... Before exporting fopen Function to open or create a file , The resulting file identifier . By default ,fopen Function to open a file for read-only access . You should specify write permissions or append , Such as 'w' or 'a'.

After processing the file , Need to use  fclose(fid)  Function to close it .

The following example demonstrates this concept :

Detailed examples

stay MATLAB Create a script file in , Enter the following code :

% create a matrix y, with two rows
x = 0:10:100;
y = [x; log(x)];
 
% open a file for writing
fid = fopen('logtable.txt', 'w');
 
% Table Header
fprintf(fid, 'Log     Function

');
 
% print values in column order
% two values appear on each row of the file
fprintf(fid, '%f    %f
', y);
fclose(fid);
% display the file created
type logtable.txt

Run the file , The following results are displayed :

Log     Function

0.000000    -Inf
10.000000    2.302585
20.000000    2.995732
30.000000    3.401197
40.000000    3.688879
50.000000    3.912023
60.000000    4.094345
70.000000    4.248495
80.000000    4.382027
90.000000    4.499810
100.000000    4.605170
原网站

版权声明
本文为[Linest-5]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220200338752.html