Chapter 11 file operation of Matlab syntax

(11.1) opening and closing of documents

fid = fopen(fileName,permission);

fid returns an integer when the file is opened successfully, and - 1 when the file is not opened successfully. permission is the opening mode of the file, 'r' represents opening in read mode (default), 'w' represents opening in write mode, 'r +' represents opening in read-write mode, and 'a' represents opening in append mode.

status = fcolse(fid);

fid indicates the identification number of the file to be closed. If fid is all, all open files (except standard files such as screen and keyboard) will be closed. If the shutdown is successful, the status returns 0. If the shutdown is unsuccessful, the status returns - 1.

(11.2) reading and writing of text files

[A,count] = fscanf(fid,fmt,size); %read
count = fprint(fid,fmt,A); %write

A is used to store read-write data. count indicates the number of data unit elements read and written successfully. fmt can control the read data format, '% d' represents an integer, '% f' represents a floating point number,'e 'represents scientific counting,'% c 'represents a character,'% s' represents a string, and the width can be specified after%, such as: '% 3d' and '% 10.5f'. Size is used to specify the size of a, n means to specify n data, inf means to specify all data, and [m,n] means to specify m × N data.

Example: now there is a group of data as follows. Read the first 6 lines of data in the file (note that the encoding method when saving the file should be changed to ANSI).

clc;clear;
fid = fopen('data.txt','r');
title = fscanf(fid,'%s',6); %Read header row
cache = cell(3,6); %Use 3×6 Cell array to accept read data
for i = 1:3
    cache{i,1} = fscanf(fid,'%s',1);
    cache{i,2} = fscanf(fid,'%s',1);
    cache{i,3} = fscanf(fid,'%f',1);
    cache{i,4} = fscanf(fid,'%f',1);
    cache{i,5} = fscanf(fid,'%f',1);
    cache{i,6} = fscanf(fid,'%s',1);
end
disp(cache);
fclose(fid);
>>
    '1 January 1'    'NW'     [2.2000]    [2.3000]    [1024]    'Sunny to cloudy'
    '1 February 2'    'W'      [1.5000]    [     3]    [1022]    'Sunny to cloudy'
    '1 March 3'    'SSE'    [     1]    [2.6000]    [1020]    'Sunny to cloudy'

(11.3) reading and writing of binary files

[A,count] = fread(fid,size,precision,skip); %read
count = fwrite(fid,A,precision); %write

A is used to store read-write data. count indicates the number of data read and written successfully. precision is used to specify the type of read and write data, such as' double '. Size indicates the size of A. Skip indicates to skip some data periodically in proportion. The default value is 0.

(11.4) document pointer position control

fseek(fid,offset,origin); %Change the position of the file pointer

offset indicates the number of bytes that the file pointer moves relative to each other. origin represents the reference position where the file pointer moves, 'cof' or 0 represents the current position of the file pointer, 'bof' or - 1 represents the beginning position of the file, 'eof' or 1 represents the end position of the file.

position = ftell(fid); %Query the current position of the file pointer
status = feof(fid); %Judge whether the current file pointer reaches the end of the file. Yes(status=1),no(status=0)

(11.5) reading and writing of CSV file

csvwrite(fileName,M,row,col); %Sets the matrix from the specified row and column offsets M Separated by commas(CSV)Write to file as(Rows and columns start at 0)
M = csvread(filename,R1,C1,[R1 C1 R2 C2]); %Read only row offsets R1 and R2 Column offset C1 and C2 Defined scope
clc;clear;
fileName = 'data.csv';
row = 1;col = 1;M = magic(4);
csvwrite(fileName,M,row,col);
type(fileName); %The data in the view file can only be files containing numeric data
A = csvread(fileName)
B = csvread(fileName,2,2)
C = csvread(fileName,2,2,[2,2,3,3])
>>
    ,,,,
    ,16,2,3,13
    ,5,11,10,8
    ,9,7,6,12
    ,4,14,15,1
A =
    0     0     0     0     0
    0    16     2     3    13
    0     5    11    10     8
    0     9     7     6    12
    0     4    14    15     1
B =
    11    10     8
     7     6    12
    14    15     1
C =
    11    10
     7     6

(11.6) reading and writing of text file

clc;clear;
fileName = 'data.txt';
M = magic(3)*pi;
N = magic(4)*pi;
%Adjacent elements are divided by tabs, and each element is displayed with 3 significant digits
dlmwrite(fileName,M,'delimiter','\t','precision',3);
type(fileName);
%Write the file in append mode, the line offset of 1 line, with“;"Divide adjacent elements and display three decimal places
dlmwrite(fileName,N,'-append','delimiter',';','roffset',1,'precision','%.3f');
%delimiter You can also',',';','\t',' ',coffset Control column offset
type(fileName);
>>
    25.1 3.14 18.8
    9.42 15.7 22
    12.6 28.3 6.28

    25.1 3.14 18.8
    9.42 15.7 22
    12.6 28.3 6.28
    ;;;
    50.265;6.283;9.425;40.841
    15.708;34.558;31.416;25.133
    28.274;21.991;18.850;37.699
    12.566;43.982;47.124;3.142
clc;clear;
fileName = 'data.txt';
M = magic(3);
N = magic(4);
dlmwrite(fileName,M,'delimiter',' ');
dlmwrite(fileName,N,'delimiter',' ','-append','roffset',1);
type(fileName);
A = dlmread(fileName,' ')
B = dlmread(fileName,' ',1,1)
C = dlmread(fileName,' ',[1 1 2 2])

>>
    8 1 6
    3 5 7
    4 9 2
   
    16 2 3 13
    5 11 10 8
    9 7 6 12
    4 14 15 1
A =
    8     1     6     0
    3     5     7     0
    4     9     2     0
    0     0     0     0
   16     2     3    13
    5    11    10     8
    9     7     6    12
    4    14    15     1
B =
    5     7     0
    9     2     0
    0     0     0
    2     3    13
   11    10     8
    7     6    12
   14    15     1
C =
    5     7
    9     2

(11.7) reading and writing of Excel files

xlswrite('filename',A,'sheet','xlRange'); %write
[num,txt,raw] = xlsread('fileName','sheet','xlRange'); %read

A represents the matrix of data to be written. sheet can specify the worksheet of excel, which is the first worksheet by default. xlRange can specify the read / write range. By default, it is read / write from A1. num means to receive the numerical part in excel as a matrix. txt means to receive the character part of excel in the form of cell array. raw means to receive the numeric and character parts in excel in the form of cell array.

clc;clear;
fileName = 'data.xlsx';
sheet = 1;
write_range = 'A1';
read_range = 'A1:F4';
headers = {'date','wind direction','wind speed','air temperature','pressure','weather condition'};
contents = {'1 January 1','NW',2.2,2.3,1024,'fine with occasional clouds';...
            '1 February 2','W',1.5,3,1022,'fine with occasional clouds';...
            '1 March 3','SSE',1,2.6,1020,'fine with occasional clouds'};
xlswrite(fileName,[headers;contents],sheet,write_range);
[num,txt,raw] = xlsread(fileName,sheet,read_range)
>>
num =
    1.0e+03 *
        0.0022    0.0023    1.0240
        0.0015    0.0030    1.0220
        0.0010    0.0026    1.0200
txt =
    4×6 cell array
        {'date'    }    {'wind direction'}    {'wind speed'  }    {'air temperature'  }    {'pressure'  }    {'weather condition'}
        {'2021/1/1'}    {'NW'  }    {0×0 char}    {0×0 char}    {0×0 char}    {'fine with occasional clouds'}
        {'2021/1/2'}    {'W'   }    {0×0 char}    {0×0 char}    {0×0 char}    {'fine with occasional clouds'}
        {'2021/1/3'}    {'SSE' }    {0×0 char}    {0×0 char}    {0×0 char}    {'fine with occasional clouds'}
raw =
    4×6 cell array
        {'date'    }    {'wind direction'}    {'wind speed'  }    {'air temperature'  }    {'pressure'}    {'weather condition'}
        {'2021/1/1'}    {'NW'  }    {[2.2000]}    {[2.3000]}    {[1024]}    {'fine with occasional clouds'}
        {'2021/1/2'}    {'W'   }    {[1.5000]}    {[     3]}    {[1022]}    {'fine with occasional clouds'}
        {'2021/1/3'}    {'SSE' }    {[     1]}    {[2.6000]}    {[1020]}    {'fine with occasional clouds'}

ginseng Test Endowment material come source Reference sources Reference sources

  1. Scientific computing and MATLAB language Liu Weiguo Cai Xuhui Lugley He Xiaoxian China University MOOC
  2. MATLAB software and basic mathematics experiment Li Changqin Zhu Xu Wang Yongmao Ji Wanxin Xi'an Jiaotong University Press
  3. MATLAB R2018a complete self-study all-in-one Liu Hao Han Jing Electronic Industry Press
  4. MATLAB engineering and scientific drawing Zhou Bo Xue Shifeng Tsinghua University Press
  5. Matlab tutorial - image processing (Lesson 1) The first moon lights lanterns https://www.bilibili.com.
  6. Matlab tutorial - image processing (lesson 2: where is meow) The first moon lights lanterns https://www.bilibili.com.
  7. MATLAB from entry to baldness Goodall https://www.bilibili.com.
  8. Experimental course of automatic control principle Giant forest warehouse Xi'an Jiaotong University Press

Bo passenger create do : A i d e n   L e e Blog creation: Aiden\ Lee Blog creation: Aiden Lee
Special statement: the article is for learning reference only. Please indicate the source for reprint. Embezzlement is strictly prohibited!

Keywords: MATLAB

Added by crag on Wed, 05 Jan 2022 09:58:14 +0200