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

Thursday, January 23, 2020

Methods to Improve the Calculation Speed of MATLAB Programs - Part 2



Improving Performance of the Code

MATLAB programs are interpreted. Hence large MATLAB programs will take a long time to execute. The power of MATLAB is realized with its extensive set of libraries which are compiled or are carefully coded in MATLAB to utilize 'vectorization'.
The concept of vectorization will help to write efficient MATLAB code. The speed of a numerical algorithm in MATLAB is very sensitive to whether or not vectorized operations are used.

This section presents some basic considerations to writing efficient MATLAB routines. It is possible, of course, to become obsessed with performance and waste man-hours of programming time in order to save a few seconds of execution time. The ideas presented below require little extra effort, yet can yield significant speed improvements. Once you understand how to use these procedures they will become natural parts of your MATLAB programming style.


Using vector operations instead of loops


MATLAB is a matrix language, which means it is designed for vector and
matrix operations. You can often speed up your M-file code by using vectorizing
algorithms that take advantage of this design. Vectorization means converting
for and while loops to equivalent vector or matrix operations.
Simple Example of Vectorizing
Here is one way to compute the sine of 1001 values ranging from 0 to 10:
i = 0;
for t = 0:.01:10
i = i + 1;
y(i) = sin(t);

end
A vectorized version of the same code is
t = 0:.01:10;
y = sin(t);
The second example executes much faster than the first and is the way
MATLAB is meant to be used. Test this on your system by creating M-file
scripts that contain the code shown, and then using the tic and toc functions

to time the M-files.




Consider the following loop, translated directly from Fortran or C
         dx = pi/30;
         nx = 1 + 2*pi/dx;
         for i = 1:nx
            x(i) = (i-1)*dx;
            y(i) = sin(3*x(i));
         end
The preceding statements are perfectly legal MATLAB statements, but they are an inefficient way to create the x and y vectors. Recall that MATLAB allocates memory for variables on the fly. On the first time through the loop (i=1), MATLAB creates two row vectors x and y, each of length one. On each subsequent pass through the loop MATLAB appends new elements to x and y. Not only does this incur extra overhead in the memory allocation calls, the elements of x and y will not be stored in contiguous locations in RAM. Thus, any subsequent operations with x and y, even though these operations may be vectorized, will take a performance hit because of memory access overhead.
The preferred way to create the same two x and y vectors is with the following statements.
         x = 0:pi/30:2*pi
         y = sin(3*x);
The first statement creates the row vector, x, with 1 + pi/15 elements stored in contiguous locations in RAM. The second statement creates a new (matrix) variable, y, with the same number of rows and columns as x. Since x is a row vector, as determined by the preceding step, y is also a row vector. If x were, for example, a 5 by 3 matrix, then y = sin(3*x) would create a 5 by 3 matrix, y.
MATLAB is designed to perform vector and matrix operations efficiently. To take maximum advantage of the computer hardware at your disposal, therefore, you should use vectorized operations as much as possible.

Pre-allocating memory for vectors and matrices

for and while loops that incrementally increase, or grow, the size of a data
structure each time through the loop can adversely affect performance and
memory use. Repeatedly resizing arrays often requires that MATLAB spend
extra time looking for larger contiguous blocks of memory and then moving the
array into those blocks. You can often improve on code execution time by
preallocating the maximum amount of space that would be required for the

array ahead of time.
The following code creates a scalar variable x, and then gradually increases the
size of x in a for loop instead of preallocating the required amount of memory
at the start:
x = 0;
for k = 2:1000
x(k) = x(k-1) + 5;
end
Change the first line to preallocate a 1-by-1000 block of memory for x initialized
to zero. This time there is no need to repepatedly reallocate memory and move
data as more values are assigned to x in the loop:
x = zeros(1, 1000);
for k = 2:1000
x(k) = x(k-1) + 5;

end




Though MATLAB will automatically adjust the size of a matrix (or vector) it is usually a good idea to pre-allocate the matrix. Pre-allocation incurs the cost of memory allocation just once, and it guarantees that matrix elements will be stored in contiguous locations in RAM (by columns).
Consider the following (admitedly artificial) sequence of statements.
         dx = pi/30;
         nx = 1 + 2*pi/dx;
         nx2 = nx/2;
 
         for i = 1:nx2
            x(i) = (i-1)*dx;
            y(i) = sin(3*x(i));
         end
 
         for i = nx2+1:nx
            x(i) = (i-1)*dx;
            y(i) = sin(5*x(i));
         end
Since we know the size of x and y, a priori, we can pre-allocate memory for these vectors. Pre-allocation involves creating a matrix (or vector) with one vectorized statement before any of the matrix elements are referenced individually. The ones and zeros functions are typically used to pre-allocate memory.
Here is an improvement of the preceding statements with pre-allocation of memory for x and y.
         dx = pi/30;
         nx = 1 + 2*pi/dx;
         nx2 = nx/2;
 
         x = zeros(1,nx);      % pre-allocate row-vectors, x
         y = zeros(1,nx);      % and y
 
         for i = 1:nx2
            x(i) = (i-1)*dx;
            y(i) = sin(3*x(i));
         end
 
         for i = nx2+1:nx
            x(i) = (i-1)*dx;
            y(i) = sin(5*x(i));
         end
The statements x(i) = ..., and y(i) = ... still do not take advantage of possibilities for vectorization, but at least the elements of x and y are stored contiguously in RAM. We will improve the efficiency of the loops shortly. First, however, note that we could have written the pre-allocation statements as
         x = zeros(1,nx);      % pre-allocate row-vectors, x
         y = x;                % and y
The statement y = x does not mean that y will stay equal to x. It simply creates another matrix y with the same ``shape'' as x. Understanding that pre-allocation is important for efficiency will help you understand these apparently confusing twists of MATLAB programming logic.
We can further improve our loops by pulling the assignment of x out of the loops.
         x = 0:pi/30:2*pi;     % vectorized calculation of x
         nx = length(x);
         nx2 = nx/2;
 
         y = x;                % pre-allocate memory for y
 
         for i = 1:nx2
            y(i) = sin(3*x(i));
         end
 
         for i = nx2+1:nx
            y(i) = sin(5*x(i));
         end
Finally, if we're obsessed with performance, we observe that the calculation of y can also be vectorized. To do this we use the colon notation to refer to segments of the x and y vectors.
         x = 0:pi/30:2*pi;     % vectorized calculation of x
         nx = length(x);
         nx2 = nx/2;
 
         y = x;                             % pre-allocate memory for y
 
         y(1:nx2) = sin(3*x(1:nx2));        % compute first part of y
         y(nx2+1:nx) = sin(5*x(nx2+1:nx));  % and the second part
To those new to MATLAB programming, the preceding statements may appear unecessarily obfuscated. The comment statements, of course, help, but the logic behind the logic comes from a true understanding of vectorization. Once you get the hang of MATLAB's colon notation you too will come to write code like this. Whenever the speed of MATLAB code is important, there is no substitute for vectorization.


Coding Loops in a MEX-File
If there are instances where you cannot vectorize and must use a for or while
loop, consider coding the loop in a MEX-file. In this way, the loop executes
much more quickly since the instructions in the loop do not have to be

interpreted each time they execute.

Functions Are Generally Faster Than Scripts
Your code executes more quickly if it is implemented in a function rather than
a script.
Load and Save Are Faster Than File I/O Functions
If you have a choice of whether to use load and save instead of the low-level
MATLAB file I/O routines such as fread and fwrite, choose the former. load
and save have been optimized to run faster and reduce memory fragmentation.
Avoid Large Background Processes
Avoid running large processes in the background at the same time you are
executing your program in MATLAB. This frees more CPU time for your

MATLAB session.

Clearing Unused Variables from Memory
If you use pack and there is still not enough free memory to proceed, you
probably need to remove some of the variables you are no longer using from

memory. Use clear to do this.


Correct code is always more important than speed

Vectorization sometimes makes MATLAB code hard to read. If you find yourself puzzling over the code, or more importantly if you find yourself wondering if the code performs the correct calculation, then stop trying to optimize performance.
Always remember


Code that gives incorrect, or inaccurate results is useless, no matter how fast it executes.

Wednesday, February 22, 2017

Methods to Improve the Calculation Speed of MATLAB Programs - Part 1



Introduction

Speed of execution of code is an important issue for all coders. In this lecture we will discuss some programming practices to improve the performance of MATLAB code.
Analyzing Performance of the Code 

MATLAB has some built is tools to help the coder to analyse the performance of his code. The two main tools are The M-file Profiler graphical user interface and the stopwatch timer. These tools help the coder to check information on how the program is performing

The M-File Profiler

Profiler help you to analyse the performance of the code and determine where you can modify your code to improve performance. M-file Profiler, a graphical user interface that shows you where your program is spending its time during execution. The Profiler can be more useful in measuring relative execution time and in identifying specific performance bottlenecks in your code.

Running the Profiler
Use one of the following methods:
  • On the Editor tab, in the Run section, click Run and Time. If you use this method, the Profiler automatically profiles the code in the current Editor tab.
  • On the Home tab, in the Code section, click Run and Time.
  • In the Command Window, type profile viewer.



Stopwatch Timer Functions ( tic and toc)
Stopwatch functions is a tool which provide absolute time measurements of execution for your code.If you just need to get an idea of how long your program takes to run, or to compare the speed of different implementations of a program, you can use the stopwatch timer functions.. Invoking tic starts the timer, and the first subsequent toc stops it and reports the time elapsed between the two.

Syntax:
tic
run the program section to be timed
toc

Shorter programs will run too fast it may be difficult to use timer function. In this case, we can measure the time by running the program repeatedly in a loop, and then average to find the time for a single run.
tic
for k = 1:100
run the program
end
toc

Sunday, January 15, 2017

User Defined Functions in MATLAB Part-4



Function Function, Local Function, and Private Function



Function Function

A MATLAB function that accepts another function as an input is called a function function. Function handles are used for passing functions to function functions. Syntax for function function is same as simple functions, but one or more input arguments will be function handles.

Local function - Sub Function

Multiple functions within one function file is called local function. Name of function file should be name of main function. Main function can be called from the command window or any other function. Local functions are typed in any order after the main function. Local functions are only visible to other functions in the same file. 


Private Function

A private function is a function residing in a sub directory with the name private. Private functions are visible only to functions in the parent directory. They are useful when we want to limit the scope of a function. You cannot call the private function from the command line or from functions outside the parent of the private folder.

Wednesday, January 4, 2017

Anonymous and Inline Functions in MATLAB



Anonymous Functions

MATLAB's anonymous functions provide an easy way to specify a function. An anonymous function is a function defined without using a separate function file. It is a MATLAB feature that lets you define a mathematical expression of one or more inputs and either assign that expression to a function. This method is good for relatively simple functions that will not be used that often and that can be written in a single expression.
An anonymous function of any number of variables can be created by giving the @ symbol, followed by a variable list, followed by the MATLAB expression. Anonymous function can be written in Command Window, script file, or inside user-defined function. Anonymous functions can only have one expression and can only return a single variable.

To give the anonymous function a name, simply put the function's name on the left side of an equal sign and the anonymous function on the right. 
                     NAME = @(ARGLIST)EXPRESSION 
  • NAME is name of the function. (using rules for names of user-defined functions) 
  • @ - a function handle, an object that has information about the function 
  • ARGLIST is the input arguments (a comma-separated list). 
  • The body of the function, to the right of the parentheses, is a single line MATLAB expression.

Inline Functions

The inline command lets you create a function of any number of variables by giving a string containing the function followed by a series of strings denoting the order of the input variables. This method is good for relatively simple functions that can be written in a single expression. It is similar to an Anonymous Function. Inline functions cannot access variables in the work space, even if those variables are global – this is the main difference with the anonymous functions.
The expression to be evaluated is defined in single quotes, followed in order by the variables of the function also surrounded by single quotes. 
                       Name = inline(‘expression', 'arg1', ‘arg2')


Monday, December 26, 2016

User Defined Functions in MATLAB Part -2



Previous post we discussed what is a user defined function in MATLAB. This lecture we will discuss how to define a function and how to call the function in a script.



Components of a function is discussed in the previous lecture. The first statement in a function must be function definition.The basic syntax of a function definition is:

function[a, b, c]= basicmath(x,y)

Basically a function accepts an input vector, perform the operation, and returns a result. The sample function given has two input variables and three output variables. But we can also have functions without input or/and output.

Under some special occasions we may need some functions without any input or output.

Some functions will take some input arguments but will not return any output arguments. Functions to plot some shapes or curves and functions to display some message are examples.

A function can be called from the command window or inside a script or function. To run a function in command window, just type the name of comment with proper input and output arguments.



Thursday, December 1, 2016

User Defined Functions in MATLAB - Part 1



User-defined functions are similar to the MATLAB predefined functions. A function is a MATLAB program that can accept inputs and produce outputs. A function can be called or executed by another program or function. Code for a function is done in an Editor window or any text editor same way as script and saved as m-file. The m-file must have the same name as the function.

It is important that you give meaningful variable names to variables inside a function that you write, so that you and others can understand what the function does. The function M-file must be saved in your current directory.


The declaration statement 'function' is used to define the file as a function. It must be typed in lower case letters. Rules for giving function name is same as the rules for variable names.
Input arguments are typed in side the parentheses ( ). They are used to transfer data into function from calling program. Can be zero or more input arguments. 
Output arguments are typed inside the square brackets [ ]. They are used to transfer data out of function to calling program. Can be zero or more output arguments. It is important to give a meaningful variable names.

Tuesday, November 22, 2016

MATLAB Programming - Loop Control Part 2




In this lecture we will discuss more about Loop control.

- Switch – case commands

- Nested lops

- break command

- continue command

switch - case Command

There is no conditional statement used in this looping structure. It choose the code to be executed based on value of scalar or string, not just true/false. Different codes can be executed based on the value of the scalar defined in the switch command. The codes are defined using the case command.

Nested Loop

A nested loop is a loop or conditional statement placed inside another loop or conditional statement. Simply, a loop within a loop. Both for and while loops can be nested.

break Statement

The break statement terminates execution of for or while loop. Statements in the loop that appear after the break statement are not executed. In nested loops, break exits only from the loop in which it occurs. Control passes to the statement following the end of that loop.



continue Statement


The continue statement is used for passing control to next iteration of for or while loop. The continue statement in MATLAB works somewhat like the break statement. Instead of forcing termination, however, 'continue' forces the next iteration of the loop to take place, skipping any code in between.



Wednesday, October 26, 2016

MATLAB Script - Loop Control Part 1




In this lecture we will discuss about another flow control method – Loop control. A loop control is used to execute a set of commands repeatedly The set of commands is called the body of the loop.

MATLAB has two loop control techniques 
  1. Counted loops - executes commands a specified number of times. 
  2. Conditional loops - executes commands as long as a specified expression is true.
The counted loops are called ‘for’ loop and the conditional loops are called ‘while’ loop. The keyword “end” is used to show the end of a Loop.


For loop is used when the numer of iteration is known. FOR Repeats for specified number of times ALWAYS executes computation loop at least once. For loop creates a vector of the variable defined in the command and execute the body of the loop for all the values of the vector. 

The while- loop used when the number of loop iterations is unknown. Number of iteration is controlled by a condition. The condition is tested in each iteration and stop looping when it is false. While loop will execute the body of loop ONLY if while condition is met. 

Both Scripts and functions also allow to loop using for and while loops. 

Conditional Control in MATLAB Scripts with Examples




In this lecture we discuss more about programming in MATLAB. One main section in programming is flow control. There are many flow control commands in MATLAB. In this lecture we discuss the conditional flow control commands.
Conditional statements are commands that allows MATLAB to decide whether or not to execute some code that follows the statement

Conditional statements use relational operators like ==,~=,>,< (Note that are all scalar tests).

The basic syntax is


žIf the conditional expression is true, MATLAB runs the lines of code that are between the line with if and the line with end.
If the conditional expression is false, MATLAB skips the code between if and the line with else and runs the code up to end.



Wednesday, September 21, 2016

MATLAB Scripts - Examples with Electrical Engineering Applications



›
This lecture we will practice some Basic MATLAB Scripts.
›We will start with simple scripts and will discuss some electrical engineering applications.

Program to calculate Electricity bill.

w = input('Enter power of your device (in watts): ');
h = input('Enter time (in hours): ');
r = input('Enter electricity rate (in dollars per KWH): ');
ec = w * h/1000 * r;
disp(’Your Electricity bill is’)
Disp(ec)



Power transfer vs Load resistance curve


RL = 1:0.01:10;
Vs = 12;
Rs = 2.5;
P = (Vs^2*RL)./(RL+Rs).^2;
plot(RL,P)
xlabel('Load resistance')
ylabel('Power dissipated')



Torque-Speed Curve for a squirrel cage Induction Motor 

›Ns=1500; % Synchronous speed;
›R1=15.6 ;R2=14;X1=18; X2=23;Xm=260;Vt=400/sqrt(3);
›s = 0.002:0.002:1; % vector of slip
›N = Ns.*(1-s); % Speed, in RPM
›Ws = 2*pi*Ns/60; % Synchronous speed in rad/sec
›Rr = R2./ s; % Rotor resistance
›Zr = j*X2 + Rr; % Total rotor impedance
›Za = j*Xm*Zr./(j*Xm+Zr); % Air-gap impedance
›Zt = R1 + j*X1 +Za; % Terminal impedance
›Ia = Vt ./ Zt; % Terminal Current
›I2 = j*Xm*Ia./(j*Xm+Zr); % Rotor Current
›Pag = 3* (abs(I2)).^2.*Rr; % Air-Gap Power
›Pm = Pag.* (1-s); % Converted Power
›Trq = Pag/ Ws; % Developed Torque
›subplot(2,1,1)
›plot(N, Trq)
›xlabel('Speed in RPM')
›ylabel('Torque (Nm)')
›subplot(2,1,2)
›plot(Ia, Trq)
›xlabel('Load Current')
›ylabel('Torque (Nm)')


Saturday, September 10, 2016

Introduction to MATLAB Scripts



MATLAB Script or programs are sequences of MATLAB commands saved in plain text files. When you type the name of the script file at the MATLAB prompt the commands in the script file are executed as if you had typed them in command window. Code for a script is done in an Editor window and saved as m-file. 



In case your code has errors, MATLAB will show an error message in the command window, when you try to run the program . Error message will be hyperlinked to the line in the file that caused the error.
—
Script variables are added to the workspace. —If you use the same variables in another script, they will be modified by that script. —This may result in a confusing mix of variables in the MATLAB workspace. —Some times it may lead to a syntax error or may lead to subtle errors in the result.

Sunday, September 4, 2016

MATLAB Programming Tips 2 - Input and Output Commands



In this lecture we will review some common input and output commands in MATLAB. These commands are discussed in detail in previous lectures.
For detailed Lectures on Input and Output commands follow the links below.


Sunday, August 28, 2016

MATLAB Programming Tips Part 1



MATLAB program (functions and scripts) are stored as script file(.m files). This type of file contains MATLAB commands, so running it is equivalent to typing all the commands—one at a time—at the Command window prompt. You can run the file by typing its name at the Command window.


Matlab Programming Tips Part 1 from Shameer Ahmed Koya
  • Both functions and scripts are stored in .m files
  • —Type up a bunch of commands and save as filename.m
  • —Type filename in command window to run
  • Example: first_program.m
  • —The name of a script file must begin with a letter, and may include digits and the underscore character, up to 63 characters.
  • —Do not give a script file the same name as a variable.
  • —Do not give a script file the same name as a MATLAB command or function.

Tuesday, August 23, 2016

Polynomials and Curve Fitting in MATLAB



MATLAB provides a number of functions for the manipulation of polynomials. Polynomials are defined in MATLAB as row vectors made up of the coefficients of the polynomial, whose dimension is n+1, n being the degree of the polynomial. Polynomials in MATLAB vector must include all polynomial coefficients, even those that are zero.

MATLAB provides the function polyval to evaluate polynomials. MATLAB does not provide a direct function for adding or subtracting polynomials unless they are of the same order, when they are of the same order, normal matrix addition and subtraction applies. Polynomial multiplication is supported by the conv function. Where we want to divide one polynomial by another, in MATLAB we use the deconv function.

Polynomials and Curve Fitting in MATLAB from Shameer Ahmed Koya

Curve fitting is the process of adjusting a mathematical function so that it lays as closely as possible to a set of data points. MATLAB provides a number of ways to fit a curve to a set of measured data. One of these methods uses the “least squares” curve fit. This technique minimizes the squared errors between the curve and the set of measured data. The function polyfit solves the least squares polynomial curve fitting problem.

Friday, August 5, 2016

Working with Excel files in MATLAB - Part 2



Read part 1 here. We will discuss few more functions to deal with Excel files.

xlswrite ( ) – Write to Microsoft Excel spreadsheet file

xlswrite is a simple function to write data to an excel worksheet. The syntax is similar to the xlsread function
xlswrtie(‘filename’, A, ‘worksheet’, ‘range’)
The function write the values in the array A to the specified range of cells in the specified worksheet of the excel file. The array may be a numeric array, character array or a cell array depending on the data. The worksheet and range arguments are optional. If not specified, the data will be written to the first worksheet starting from A1.

Example:
No we will add marks of two more students to our grade file.
>> newstud = {342001, 'James', 12.5, 13, 20;342001, 'Anna', 12, 10.5, 16};


>> xlswrite('test.xlsx', newstud, 'A7:E8')

writetable( ) - Write table to file

wrtietable function by default write the content of martlab table to a text file in comma separated format. The file name will be automatically set if not specified.
writetable(T) is the basic syntax.
writetable(T, ‘filename’) writes the table T to the file as column-oriented data.  The function automatically determines the file format based on the extension specified in the filename.
Optional arguments to select the work sheet and range is available when you write to an excel file.
Example:
We will write the contents of the table T from the previous example to the second sheet of the same file.
>> writetable(T,'test.xlsx','sheet',2)
The command will write the data to the Sheet2.

Importdata( ) - Load data from file

importdata is used to load data from a file to the workspace. The function will recognise the file type from the extension and will call appropriate procedure to load the data.
A = importdata(‘filename’) loads data into the structure A.
Example:
>> A = importdata('test.xlsx')
A =
          data: [1x1 struct]
      textdata: [1x1 struct]
    colheaders: [1x1 struct]
To get the contents use the commands
A.data
A.textdata
A.colheaders

Friday, July 22, 2016

Working with Excel files in MATLAB - Part 1



MATLAB have many builtin functions to work with Excel files. In this post, we will discuss some of the common functions to work with Excel files.  It is easy to interact with an excel file using xlswrite and xlsread commands. First we will make an sample excel file test.xlsx which contain grades of students in a class.

xlsread ( ) - Read Microsoft Excel spreadsheet file

The xlsread function reads data from the first worksheet of a Microsoft Excel file and save the numeric data in a array. If the file contains only numeric data the syntax is:
A = xlsread(‘filename’)
The ‘filename’ is a string with full name of the excel file (with path if the file is not in the current folder). The numeric data in the first work sheet of the file will be saved to the variable A. There are optional arguments to set the work sheet and the range to be read.
A= xlsread(‘filename’, ‘worksheet’, ‘range’)
The range is specified in the same way as represented in the excel equations (e.g. C2:F12).
If the file contains nonnumeric data, the syntax is modified as:
[NUM,TXT,RAW]=xlsread(‘filename’, ‘worksheet’, ‘range’)
The dat in the file will be saved as, numeric data in the variable NUM, text data in the variable TXT and the unprocessed data will be save as a cell array RAW. The cell array RAW will contain all the data in the worksheet.

Example:
Consider the file test.xlsx, which contain the grades of students. The numeric data is stored in the range C2:F6.
>> a=xlsread('test.xlsx', 'C2:F6')
a =
   11.5000   13.0000   18.0000   42.5000
    5.7500   10.0000   15.0000   30.7500
   14.0000   12.0000   16.0000   42.0000
   10.0000    8.2500   18.0000   36.2500
   14.2500   13.0000   20.0000   47.2500
To read all the data,
>> [a,b,c]=xlsread('test.xlsx')
a =
   1.0e+05 *
    3.3213       NaN    0.0001    0.0001    0.0002    0.0004
    3.3217       NaN    0.0001    0.0001    0.0001    0.0003
    3.4104       NaN    0.0001    0.0001    0.0002    0.0004
    3.4105       NaN    0.0001    0.0001    0.0002    0.0004
    3.4105       NaN    0.0001    0.0001    0.0002    0.0005

b =
    'ID'    'Name'    'Mark 1'    'Mark 2'    'Mark 3' 'Total'
    ''      'Bob'     ''          ''          ''          ''    
    ''      'Jil'     ''          ''          ''          ''    
    ''      'John'    ''          ''          ''          ''    
    ''      'Ken'     ''          ''          ''          ''    
    ''      'Eva'     ''          ''          ''          ''    

c =
'ID'       'Name'    'Mark 1'     'Mark 2'    'Mark 3' 'Total' 
[332133]    'Bob'     [11.5000]    [  13]    [  18]  [42.5000]
[332166]    'Jil'     [ 5.7500]    [  10]    [  15]  [30.7500]
[341041]    'John'    [     14]    [   12]   [  16]  [     42]
[341046]    'Ken'     [     10]   [8.2500]   [  18]  [36.2500]
[341052]    'Eva'     [14.2500]    [   13]   [  20]  [47.2500]

readtable( ) - Create table from file


readtable function is used to read not only excel files. \it read from different file types and sane as a MATLAB table.
T = readtable(‘filename’) is the basic syntax. There are optional arguments to set the file type and many other attributes based on the type of the file.
Example:

>> T = readtable('test.xlsx')

Warning: Variable names were modified to make them valid MATLAB identifiers.

T =

        ID         Name      Mark1    Mark2    Mark3    Total

    __________    _______    _____    _____    _____    _____

    3.3213e+05    'Bob'       11.5      13     18        42.5

    3.3217e+05    'Jil'       5.75      10     15       30.75

    3.4104e+05    'John'        14      12     16          42

    3.4105e+05    'Ken'         10    8.25     18       36.25

    3.4105e+05    'Eva'      14.25      13     20       47.25

      3.42e+05    'James'     12.5      13     20        45.5

      3.42e+05    'Anna'        12    10.5     16        38.5


Like in the xlsread function, read table also have optional arguments to read a specific worksheet and range. For more details refer Matlab Help.

Friday, July 15, 2016

Working with Text files in MATLAB - Part 2



In part one we discussed about basic functions to deal with text files. Now we will discuss more function to read from and write to different types of text files.

csvwrite( )  - Write comma-separated value file

csvwrite is the basic function in MATLAB to write data to a file as comma-separated values. It has only limited options to write numeric data to the file. The syntax is:
csvwrite(filename, C)
The function writes matrix C into the file as comma-separated values.

Example:
>> csvwrite('csvexample.txt',data)
Write the contents of the variable data to the file csvexample.txt as comma separated values.
If you want to write with more formatting options, you have to use fprinf or dlmwrite functions.

csvread( ) - Import Comma-Separated Data

Like csvwrite function, csvread also is simple function to read a .csv file or range of comma-separated numeric data and save to a matrix. The file must contain only numeric values.
X = csvread('filename')
Other optional arguments are offset and range.
X = csvread('filename', R, C, [range])
Where R and C are the row and column offsets and the range is row and column numbers of left top and right bottom points defined as range = [R1 C1 R2 C2].
Example:
To read the data from the csvexample.txt file we made in the previous example:
>> A=csvread('csvexample.txt')
A =
     1     2     3     4
     5     6     7     8
     9    10    11    12

dlmwrite( ) - Write matrix to ASCII-delimited file

dlmwrite function also is used to write the data in to a file. But it has more options than the csvwrite function. The syntax is:
dlmwrite('filename', C, 'delimiter', ’value’, R, C)
The function writes the contents of matrix C in to the file.  The delimiter is used to separate the values. The default delimiter is ‘,’ (comma). You can us other values also as the delimiter. The offset values R and C are optional.
There are optional user configurable attributes available to have more control over writing the data. ‘-append’ , ‘precision’, ‘newline’ are some commonly used attributes.
Example:
>> dlmwrite('dlmexample.txt',data)
Will write the contents of the variable data to the file dlmexample.txt as shown below
1,2,3,4
5,6,7,8
9,10,11,12
Now if we modify our command using different delimiter the file will be updated as:
>> dlmwrite('dlmexample.txt',data,'delimiter',';')
1;2;3;4
5;6;7;8
9;10;11;12
Note that the delimiter is changed to semi-colon.
>> dlmwrite('dlmexample.txt',data,'delimiter','\t')
1   2   3   4
5   6   7   8
9   10  11  12
Now the de limiter is the tab.
dlmwrite('dlmexample.txt',data,'delimiter','\t','precision','%.6f')
1.000000    2.000000    3.000000    4.000000
5.000000    6.000000    7.000000    8.000000
9.000000    10.000000   11.000000   12.000000
The ‘precision’ attribute is used to set the number of significant digits to 6.

dlmread( ) - Import Delimited Numeric Data

This function is used to read a file or a range of numeric data separated by any delimiter to a matrix. The file must contain numeric data only. The Syntax is:
X = dlmread(‘filename, ‘delimiter’, [range])
Delimiter and range are optional. If the delimiter argument is not specified, then the delimiter is inferred from the formatting of the file (consecutive white spaces are treated as a single delimiter). Range is to define the range of data to be read from a file, as explained in the csvread section.
Example:
>> A=dlmread('dlmexample.txt')
A =
     1     2     3     4
     5     6     7     8
     9    10    11    12
To read only 3rd row of the file:
>> A=dlmread('dlmexample.txt','\t', [2 0 2 3])
A =
     9    10    11    12

type( ) - Display contents of file

type is the function to display the contents of a file in the command window. The contents of the file may be numeric or non-numeric. The syntax is:
type ‘filename’

Example:
>> type 'dlmexample.txt'
1.000000  2.000000  3.000000  4.000000
5.000000  6.000000  7.000000  8.000000
9.000000  10.000000 11.000000 12.000000

>> type 'texttest.txt'
Welcome to Electrical Engineering Tutorial

>> type 'test.txt'
% This is a grade file
     jim 99 87 98
     jess 94 92 91

     jenna 100 90 95