Page 840 - Mechatronics with Experiments
P. 840
826 MECHATRONICS
Example: Working with Excel Files Data from an Excel file can be entered to
®
a MATLAB variable by specifying the (Figures A.4 and A.5)
1. Excel filename,
2. Worksheet name in the file,
3. optionally a specified range of rows and columns in the spreadsheet and assign it to
®
a MATLAB variable.
Let us assume that we have an Excel file with three colums of data, first column
represents the “time,” the second column represents the “force,” and the third column
represent the “position”. At the very top of the file, in row 1, we have the text information
on top of colums 1, 2, 3 as “time,” “force,” “position,” respectively. Our objective is to
read the numeric data interactively, plot the results, and modify the data, and then write the
modified data by appending it to colums next to the existing data on the same worksheet.
Plot the data in “position versus time” and “force versus time,” then multiply the “force”
data by 2 and position data by 3, save the new data into the same file into columns 5, 6, 7
as “time,” “force,” “position.” Before running this program, make sure Excel program does
not have the data file “myExcelDataFile1.xls” open. The host PC should have the Excel
program installed in order to run the program properly.
% Filename; myExcelFile1.m
disp(’Reading Excel Data File...’) ;
myData = xlsread(’c:\temp\myExcelDataFile1.xls’,-1);
disp(’Completed reading...’);
subplot(221)
plot(myData(:,1), myData(:,2))
ylabel(’Position’);
xlabel(’Time’);
subplot(222)
plot(myData(:,1), myData(:,3))
ylabel(’Force’);
xlabel(’Time’);
myData2(:,2) = 2.0 .∗ myData(:,2) ;
myData2(:,3) = 3.0 .∗ myData(:,3) ;
subplot(223)
plot(myData(:,1), myData2(:,2))
ylabel(’Position’);
xlabel(’Time’);
subplot(224)
plot(myData(:,1), myData2(:,3))
ylabel(’Force’);
xlabel(’Time’);
disp(’Writing Excel Data File...’);
xlswrite(’c:\temp\myExcelDataFile1.xls’, myData2, ’Sheet1’, ’E2’) ;
xlswrite(’c:\temp\myExcelDataFile1.xls’, myData2, ’Sheet2’, ’A2’) ;
disp(’Competed writing...’);
The ease of plotting in MATLAB ® is one of the most attractive features of it. In
plotting data, we need to open a figure window, divide the window into subplot areas if
desired, define the title, labels of x and y axes, scales of x and y axes, and for each x-y pair of
data we can specify the line type and color. These are illustrated in the following example.
% open a new figure window
% 2x3 grid of sub-plot areas in the figure,