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.



Thursday, May 26, 2016

Working with Files in MATLAB - Part 1

In this post we will discuss some basic functions to work with external files using MATLAB. Matlab can interact with many popular file fromats. The common file formats are Excel® spread sheets, text, images, audio and video, XML documents and scientific data formats. In addition to the functions to directly work with these file format, there are low-level file I/O functions which work with data files in any format.

Open( ) - Open the files with extension

The open command is used to open a file available in the Matlab path. The file name is specified with the extension. This function is used to open almost all common file types. The syntax is:
open NAME
where NAME is the filename with extension. If the extension is not specified, it will search for a variable with name NAME and if not found only look for the files. The path for the file also can be used in the command. If the file is not found in the Matlab path of the specified path, the function will give an error message.
Figure shows the outputs of the different open commands.
open test.txt
open test.docx
open test.pptx
open test.xlsx

If the file extension is not specified it will give an error message
open test
Error using open (line 102)
File 'test' not found.

fopen( ) - Open file with access permission

fopen( ) is the function used to open the files located in the current folder or Matlab path with assigned permission modes. The syntax is;
FID = fopen(‘Filename’, ’Permission’)
The command opens the file Filename in the mode specified by Permission. Default mode of permission is ‘read access’. The file name is specified as a string with extension. The file name may include the path of the file. FID is a scalar MATLAB integer valued double, called a file identifier. The codes used for the permission are given below.
         'r'     open file for reading
        'w'     open file for writing; discard existing contents
        'a'     open or create file for writing; append data to end of file
        'r+'    open (do not create) file for reading and writing
        'w+'    open or create file for reading and writing; discard
                existing contents
        'a+'    open or create file for reading and writing; append data
                to end of file
        'W'     open file for writing without automatic flushing
        'A'     open file for appending without automatic flushing

no = [1 2 3];
id = [331560  331566  332563];
A= [no; id];
fileID = fopen('test.txt','w');
fprintf(fileID,'%6s %12s\n','No','ID');
fprintf(fileID,'%6.0f %12.0f\n',A);

The script open the file test.txt and write the data in to the file. 
The fclose( ) function is used to close the file.  
If the file is opened in update mode ('+'), we have to use fseek( ) or frewind( ) between other commands for entering data(input) to or reading(output) data from the file.

[FID, MESSAGE] = fopen('Filename') can be used to return a system dependent error message if the open is not successful.
[FID, MESSAGE] = fopen('data.txt')
No such file or directory

fclose( ) - Close the file

fclose(FID) closes the file associated with file identifier FID. The FID must me the same variable name used with the fopen( ) command.  If FID does not represent an open file, or if it is equal to 0 (standard input), 1 (standard output), or 2 (standard error), fclose(FID) returns an error.
 >> s=fopen(FID)
s =
C:\Users\skoya\Google Drive\Matlab Work\test.txt
s = fclose('all')

closes all open files, except 0, 1 and 2.

Tuesday, May 17, 2016

Data Display and Output Commands in MATLAB

disp( )

'disp' is the basic command used to display value of a variable or a string. It can display value of only one variable or a string at a time. It can’t display multiple values in single command.
disp(A) displays the value of variable A without printing the variable name. The argument can be a string, a numeric or an expression. If the variable contains an empty array, returns without displaying anything.
>> A = [1 2 3 4 5];
>> disp (A)
     1     2     3     4     5
>> disp([1 2 3 4 5])
     1     2     3     4     5
>> S = 'Electrical';
>> disp(S)
>> disp('Electrical')
>> disp(A.*2)
     2     4     6     8    10
If the data is mixed with numeric and text, you have to use multiple disp commands.
>> disp('Today is April'), disp(1)
Today is April
Here the text and the number are displayed in different lines. They can be printed in the same line with following code
>> m = ['Today is April ', num2str(1)];
>> disp(m)
Today is April 1
Tips: Display Hyperlink in Command Window
Display a link to a Web page by including HTML hyperlink code as input to disp. For example, display a link to my blog site.
>> X = '<a href = "http://electricalenggtutorial.blogspot.com"> Electrical Engineering Tutorial</a>';
>> disp(X)

Electrical Engineering Tutorial

fprintf( )

'fprintf' is used to formats data and displays the results on the screen and to write the data in to a text file. It can mix numbers and text in output and have full control of output display formats.
fprintf(‘text’) will display the text in the command window without any formatting. This is the simple form of the function. 
fprintf(format, A, ...) formats data stored in the variable A and displays the results on the screen.
fprintf(FID, format, A, ...) applies the format to all elements of array A and any additional array arguments in column order, and writes the data to a text file.  FID is an integer file identifier.
>>fprintf('Matlab Programing Tips')
Matlab Programing Tips>>
Note that the next prompt is coming in the same line. This can be solved by inserting \n after the text.
>> fprintf('Matlab Programing Tips\n')
Matlab Programing Tips
\n can be used to display the text in multiple lines. This is done by inserting \n before the character that will start the new line. For example, insert \n after each word in the previous example.
>> fprintf('Matlab\n Programing\n Tips\n')
When a program has more than one fprintf command, the display generated is continuous (the fprintf command does not automatically start a new line). The following lines are from a script file.
>> fprintf('Matlab Programing Tips')
>> fprintf('are very useful\n')
the program will give an output in the command window as:
Matlab Programing Tipsare very useful

Formatting Operator
To display data in a variable, the formatting operators are used. A formatting operator starts with a percentage sign, %, and ends with a conversion character. The table shows conversion characters to format numeric and character data as text.

Value Type
Integer, signed
%d or %i
Base 10
Integer, unsigned
Base 10
Base 8 (octal)
Base 16 (hexadecimal), lowercase letters a–f
Floating-point number
Fixed-point notation (Use a precision operator to specify the number of digits after the decimal point.)
Exponential notation, such as 3.141593e+00 (Use a precision operator to specify the number of digits after the decimal point.)
The more compact of %e or %f, with no trailing zeros (Use a precision operator to specify the number of significant digits.)
Single character
Character vector

>> age = 35;
>> weight = 75.25;
>> fprintf( 'Joe is %d weighs %f kilos\n', age, weight )
Joe is 35 weighs 75.250000 kilos
%d defines age as an integer and %f defines weight as floating point number.

The optional identifier, flags, field width, precision, and subtype operators further define the format of the output text.
·         Identifier – defines the order for processing the function input arguments. Use the syntax n$, where n represents the positions of the other input arguments in the function call.
·         Flag - can be one of the following three characters:
–          Left-justifies the number within the field.
+          Prints a sign character (+ or –) in front of the number.
0          Adds zeros if the number is shorter than the field.
·         Field Width - Minimum number of characters to print. The function pads to field width with spaces before the value.
·         Precision - specifies the number of digits to be displayed to the right of the decimal point.
>> fprintf( 'Joe weighs %4.4f kilos\n', weight )
Joe weighs 75.2500 kilos
>> fprintf( 'Joe weighs %4.2f kilos\n', weight )
Joe weighs 75.25 kilos
%4.4f in the format specifies that the value as a floating-point number with a field width of four digits, including four digits after the decimal point. %4.2f in the format specifies that the value as a floating-point number with a field width of four digits, including two digits after the decimal point.

Writing data to a File
Write a short table of the exponential function to a text file called exp.txt.
x = 0:.1:1;A = [x; exp(x)];fileID = fopen('exp.txt','w');
fprintf(fileID,'%6s %12s\n','x','exp(x)');
fprintf(fileID,'%6.2f %12.8f\n'
The script open the file exp.txt and write the values of the x and exp(x) to the file.
fprintf(fileID,'%6s %12s\n','x','exp(x)') is used to set the header for each column. %6 define the width a 6 for values of x and %12 define the width as 12 for exp(x). fclose command is used to close the file.
Some special characters are used as format operators. So we can’t use those characters as ordinary text. This table shows how to represent special characters.
Special Character Representation
Single quotation mark ''
Percent character %%
Backslash \\
Alarm \a
Backspace \b
Form feed \f
New line \n
Carriage return \r
Horizontal tab \t
Vertical tab \v
Character whose ASCII code is the hexadecimal number, N \xN
Character whose ASCII code is the octal number, N \N

sprintf( )

'sprintf' is the same as fprintf except that it returns the data in a Matlab string rather than writing to a file.
str = fprintf(format, A, ...) formats data stored in the variable A and return to the variable str.
>> w = sprintf( 'Joe weighs %2.4f kilos\n', weight )
w =
Joe weighs 75.2500 kilos

Msgbox( )

msgbox(‘Message’) creates a message box with a OK button that contains the Message to be displayed. The size of the figure is automatically fit to wrap the message. The argument ‘Message’ may be a string vector, string matrix or cell array.
age = 35;
weight = 75.25;
msgbox( sprintf( 
'Joe Age is %d years \n Weight is %2.2f kilos', age, weight ))
The message box title and type can be set by the additional optional parameters.
msgbox(‘Message’,’Title’,’Icon’) specifies the Title of the message box and Icon to display in  the message box.  Icon is 'none', 'error', 'help', 'warn', or  'custom'. The default is 'none'. This can be used to create the error or warning messages in the programs.
>> msgbox('The ID you entered in Invalid','Invalid ID','error');

Tips: The error and warning messages can be made by dedicated commands 'errordlg( ) and warndlg( )

Tuesday, May 10, 2016

Basic Data Input Commands in MATLAB

We have discussed about different types of variables in Matlab and different ways to assign data to them. Now we will discuss how to display the data stored in the variable to the command window or save it to a file. 


Input is the simple basic command to request the user input. It displays a prompt text for the user to understand what data to be entered and waits for the user to input a value and press the Return key. The user can enter numbers, expressions, or variables in the workspace. If the data required is a string, then it must be specified in the input command as shown in the syntax below.

If the data is a numeric,             
x = input('prompt')
The ‘prompt’ is the message to be displayed in the command window. The entered data is stored to the variable x. If the user enters a non-numeric or an invalid expression, then MATLAB® displays the relevant error message, and then redisplays the prompt. If the user presses the Return key without entering anything, then input returns an empty matrix.

If the data is a string,     
str = input('prompt','s')
The entered text is stored to the variable str as a string

Input Dialog Box

Dialog box is another method to take the input from the user. Inputdlg is the command to create dialog box that gathers user input. The advantage of input dialog box is that it can gather multiple data in single step.

Datain  = inputdlg('prompt')

Datain = inputdlg('prompt', 'title', num_lines, 'default', options)
The inputdlg command creates a dialog box for the user input and returns user input for multiple prompts.

Arguments other than prompt is optional. 'title' specifies a title for the dialog box, num_lines specifies the number of lines for each user input data and 'default' specifies the default value to display for each prompt. 'default' must contain the same number of elements as prompt and all elements must be of type char.
If the user clicks the Cancel button to close an inputdlg box, the dialog returns an empty cell array.

Example 1
Example 2
prompt = {'Enter Your Name:','Enter Your ID:'};
title = 'User Data';
num_lines = 1;
userdata = inputdlg(prompt,title,num_lines);
Example 3
Create a dialog box to display input fields of different widths.
x = inputdlg({'Name','Telephone','Account'},'Customer', [1 50; 1 12; 1 7]); 


sscanf provides more control over reading data in the form of a string. It read all data as string and convert to the other formats based on the definition in the command.

X = sscanf(str, format, size)
The sscanf(str, format) reads data from the vector str, converts it according to the format, and store the results in array X. Argument ‘size’ is optional. If not specified the function scan the string and pplies the format until the end of str or failing to match the format. If sscanf cannot match the format to the data, it reads only the portion that matches into X and stops processing. If str is a character array with more than one row, sscanf reads the characters in column order.

Example 1
Read multiple floating-point values from a character vector:
str = '1.234  3.456';

X = sscanf(str,'%f')
X =
Example 2
a= '1 2 3';

A = sscanf(a, '%d', 2)    % the size is defined as 2 and converted to double format.
A =