A blog to help electrical engineers and students to learn electrical engineering topics. Basic Electrical Engineering, Power Systems, Electrical Machines, tec.. Now special course on MATLAB for Beginners.

Class

Class

Saturday, June 25, 2016

The load and save Functions



Load( ) - Load data from MAT-file into workspace

The variables in the workspace are saved by default as matlab.mat file. The load command loads these variables to the workspace. If the variables are stored in a specific file, use the syntax:
S = load(‘Filename’).
The command loads the variables from a Filename.mat file into a structure array named S. If the file is not .mat file, it will be considered as an ASCII file and load data into a double-precision array. ASCII files must contain a rectangular table of numbers, with an equal number of elements in each row.  The file delimiter can be a blank, comma, semicolon, or tab. 
If the file has multiple variables, we can load some specific variables from the file using,
S = load(‘filename’, ‘variable1’, ‘varible2’, …)
Use the '*' wildcard to match patterns.  For example, load('A*') loads all variables that start with A.
Examples:
Consider vasriables a,b and c saved to default matalab.mat and variables x, y and z are save to test.mat file.
>> load
Loading from: matlab.mat
Load the variables a b and c to the workspace.
>> load test.mat
Load the varibles x y and z to the workspace.
>> S = load('test.mat')
S =
    x: [1 2 3 4 5]
    y: [1 2 3 4 5 6 7 8 9 10]
    z: 'ElectricalEngineering'
The command load the values x y and z to the structure S.
>> P = load('test.mat', 'x')
P =
    x: [1 2 3 4 5]
Load only value of x to the structure P.

save( ) - Save workspace variables to file

The save command is used to save all the variables in the work space to the matlab.mat file. The variables can be asved to some specific file using,
save(’filename’).
The command stores all the variables in the current workspace in a file named filename.mat. If the filename does not include a full path, MATLAB create the file in the current folder.
We can save selected variables only using,
save(‘filename’, ‘veriable1’, ‘variable2’, …).
If we use the save command in the command window, the bracket and the single quotations are not required. The filename can be entered directly after the save with a space in between. Separate input variables with spaces instead of commas.
There are more optional arguments to define the type of the file and the way of storing the variables.
'-struct' – is used to save the fields of the specified structure as individual variables. Specific fields of the structure can be selected by adding the field names after the structure name.
save(‘filename’, '-struct', ‘Structname’, ‘Fieldname’)
'-mat' or '-ascii' – used to specify the format of the file. By default the save will use .mat format. For more options on format, refer Matlab help.
'-append' – used to adds new variables to an existing file,    adds data to the end of the file.
Examples:
Default save command save all the variables to the Matlab.mat file
>> save
Saving to: matlab.mat
>> open('matlab.mat')
ans =
    x: [1 2 3 4 5]
    y: [1 2 3 4 5 6 7 8 9 10]
    z: 'ElectricalEngineering'
    S: [1x1 struct]
    P: [1x1 struct]
 Save only variables x and y to xydat.mat
>> save('xydata.mat', 'x', 'y')
>> open('xydata.mat')
ans =
    x: [1 2 3 4 5]
    y: [1 2 3 4 5 6 7 8 9 10]
Save the fields of a structure as individual variables:
>> save('newstruct.mat', '-struct', 'S')
>> open('newstruct.mat')
ans =
    x: [1 2 3 4 5]
    y: [1 2 3 4 5 6 7 8 9 10]

    z: 'ElectricalEngineering'

Saturday, June 11, 2016

Working with Files in MATLAB - Part 3



fwrite( ) - Write binary data to file

fwrite function is used to  write the elements of matrix A to the specified file. The data are written in column order. After write action the pointer will be set to the end of the file.
Count = fwrite(FID, A, ’precision’) format the elements of matrix A to the specified data type defined by precision and write to the file specified by FID.
The optional argument ‘precision’ is similar to the fread function. It defines the format and size of the data written to the file. The default data type is ‘unit8’.
Example:
The following example open the file test.txt and write the data stored in the variables X, Y and Z in the previous example in to it.
>> fileID = fopen('test.txt','wt');
>> fwrite(fileID,X,'char');
>> fwrite(fileID,Y,'char');
>> fwrite(fileID,Z,'char');

Both fread and fwrite functions include another optional argument SKIP, that specifies the number of bytes to skip before the read or write action. If the SKIP argument is present, the fwrite function skips some data and writes a value, skips and writes another value, etc. until all of A is written.


fgets( ) and fgetl( ) - Read a line of data from the file

Both the functions read a complete line of data from a file. The difference is in the way they store the end of line/ new line characters like \n ,\r etc.
fgets - keep the newline characters
fgetl - discard the newline characters
Both A = fgets(FID)  or A= fgetl(FID) read a full line of data in a file defined by FID and saves the data in to the variable A. If just an end-of-file is encountered then -1 is returned. If an error occurs while reading, the function returns an empty string.
Example:
>> fileID = fopen('test.txt','rt');
>> A =fgets(fileID)
A =
Welcome to Electrical
>> A =fgets(fileID)
A =
Engineering
>> A =fgets(fileID)
A =
Tutorial
The difference between fgets and fgetl can be understood only with the files that contain newline characters. If there is no new line character, both functions will give same result. Given a file with no newline characters, fgets may take a long time to execute.
Example:
If there is an end of line character ‘\n’ after the first line of the previous example, the result of both functions are given below:
>> A =fgets(fileID)
A =
Welcome to Electrical\n
>> A =fgets(fileID)
A =
Welcome to Electrical

Saturday, June 4, 2016

Working with Files in MATLAB - Part 4



fseek( ) - Set file position indicator

fseek is the function used to set the position indicator to the byte with the specified Offset relative to the given Origin.
S = fseek(FID, Offset, Origin) relocate the file position pointer in the file associated with the given FID.
Offset value may be positive or negative integers. If the value is positive the pointer will be moved after the Origin and if the value is negative the pointer will be mover before the Origin.
Origin may be starting of the file ('bof' or -1), end of the file ('eof' or  1) or current pointer position ('cof' or  0).  
Example:
>> fileID = fopen('test.txt','rt');
>> A =fseek(fileID, 7, -1)
Relocate the file position pointer to the point after the text Welcome in the file.
>> fseek(fileID, 0, -1)
rewinds the file.

frewind( ) -  Rewind the file

frewind(FID) sets the file position indicator to the beginning of the file.

ftell( ) - Get file position indicator. 

ftell function is used to get the current position pointer position of the file.
P = ftell(FID) returns the location of the file position indicator in the specified file.  Position is indicated in bytes from the beginning of the file.  P will be a non-negative integer. If -1 is returned, it indicates that the query was unsuccessful. Use FERROR to determine the nature of the error.
>> fseek(fileID, 7, -1);
>> ftell(fileID)
ans =
     7

Working with Files in MATLAB- Part 2



In the last post we discussed how open and close the external files by MATLAB. In this post we will discuss some low level read and write functions to work with external files. Read Part 1 Here.
Low level I/O functions are used to read or write data to a file. It gives more control over the I/O operation if you have the full details of the file. The file must be opened before using these commands.

fscanf( ) - Read formatted data from a text file


fscanf is the basic low level I/O function like fprintf. It is used to read an entire file with some specified formatting.
[A, count] = fscanf(FID, ‘format’, size) reads the data throughout the entire file, convert it to a format defined by ‘format’ and save into the array A in column order. FID is the file identifier obtained from fopen( ) command. ‘format’ is a string containing the conversion specifications (which include a % character, an optional * to skip over the matched value, an optional width field and a conversion character as we discussed in fprintf).
The optional part, count, is an output argument that gives the number of elements successfully read. The size defines the dimensions of the output variable. If the function can’t match the ‘format’ to the data, it reads only the portion that matches and then stops processing.
The example below is used to read the numeric data in a text file.


fscanf can be used to read the text also as shown in the example below.


 

fread( ) -  Read binary data from file


fread function is mainly used for reading binary data.
X = fread(FID, size, ‘precision’) reads specified number of binary data from the file and writes it into matrix A.  MATLAB reads the entire file byte by byte and positions the file pointer at a point specified by the size or at the end of the file.
The argument size is optional. The optional argument ‘precision’ is to specify the type of the data to be read. It is a string contains data type specifier like 'int' or 'float', followed by an integer giving the size in bits. If not specified, the default data type is 'uint8'. If the precision is 'char' or 'char*1', MATLAB reads characters.
If an error occurs before reaching the end of file, only full elements read up to that point are used.
By default, numeric and character values are saved as 'double' arrays. To save the data in a data type other than double, modify the precision argument by first specifying the source format, then following it by '=>', and finally specifying the destination format.
For example,
        ‘double=>uint8’              Read in doubles, convert and save as an unsigned 8-bit integer
Examples:
Consider the texttest.txt file used in the pre3vious example.
>> fileID = fopen('texttest.txt','rt');
>> X= fread(fileID,7)

X =
    87
   101
   108
    99
   111
   109
   101
>> frewind(fileID)
>> X= fread(fileID,7,'uint8=>char')
X =
W
e
l
c
o
m
e
In the above example, when we used the default data type, the characters in the file are saved as numeric, the ASCII code of each character. When the precision is set to save as character the elements in the vector X is saved as characters. After the fread function is executed the file pointer will be at point after the letter ‘e’. frewind( ) is used to set the file pointer back to the start of file position. If we use the fread function without frewind, the file will be read from the current position of the file pointer. See the example below.
>> X= fread(fileID,7,'uint8=>char')'
X =
Welcome
>> Y = fread(fileID,4,'uint8=>char')'
Y =
 to
>> Z = fread(fileID,10,'uint8=>char')'
Z =
Electrical