100% found this document useful (1 vote)
4K views

[Ebooks PDF] download Introduction to MATLAB and SIMULINK A Project Approach Third Edition Engineering Ottmar Beucher full chapters

Ottmar

Uploaded by

tendifenyep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
4K views

[Ebooks PDF] download Introduction to MATLAB and SIMULINK A Project Approach Third Edition Engineering Ottmar Beucher full chapters

Ottmar

Uploaded by

tendifenyep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Visit https://ebookfinal.

com to download the full version and


explore more ebook

Introduction to MATLAB and SIMULINK A Project


Approach Third Edition Engineering Ottmar Beucher

_____ Click the link below to download _____


https://ebookfinal.com/download/introduction-to-matlab-
and-simulink-a-project-approach-third-edition-
engineering-ottmar-beucher/

Explore and download more ebook at ebookfinal.com


Here are some recommended products that might interest you.
You can download now and explore!

An Introduction to Numerical Methods A MATLAB Approach


Third Edition Guenther

https://ebookfinal.com/download/an-introduction-to-numerical-methods-
a-matlab-approach-third-edition-guenther/

ebookfinal.com

System Simulation Techniques with MATLAB and Simulink 1st


Edition Dingyü Xue

https://ebookfinal.com/download/system-simulation-techniques-with-
matlab-and-simulink-1st-edition-dingyu-xue/

ebookfinal.com

Introduction to the Simulation of Dynamics Using Simulink


1st Edition Michael A. Gray

https://ebookfinal.com/download/introduction-to-the-simulation-of-
dynamics-using-simulink-1st-edition-michael-a-gray/

ebookfinal.com

Signals and Systems with MATLAB Computing and Simulink


Modeling 3rd Edition Steven T. Karris

https://ebookfinal.com/download/signals-and-systems-with-matlab-
computing-and-simulink-modeling-3rd-edition-steven-t-karris/

ebookfinal.com
Modeling and Simulation in Ecotoxicology with Applications
in MATLAB and Simulink Kenneth R. Dixon

https://ebookfinal.com/download/modeling-and-simulation-in-
ecotoxicology-with-applications-in-matlab-and-simulink-kenneth-r-
dixon/
ebookfinal.com

Modeling and Simulation of Systems Using MATLAB and


Simulink 1 Har/Cdr Edition Devendra K. Chaturvedi

https://ebookfinal.com/download/modeling-and-simulation-of-systems-
using-matlab-and-simulink-1-har-cdr-edition-devendra-k-chaturvedi/

ebookfinal.com

Chemical Engineering Dynamics An Introduction to Modelling


and Computer Simulation Third Edition Dr. John Ingham

https://ebookfinal.com/download/chemical-engineering-dynamics-an-
introduction-to-modelling-and-computer-simulation-third-edition-dr-
john-ingham/
ebookfinal.com

Engineering Materials 2 Third Edition An Introduction to


Microstructures Processing and Design D R H Jones

https://ebookfinal.com/download/engineering-materials-2-third-edition-
an-introduction-to-microstructures-processing-and-design-d-r-h-jones/

ebookfinal.com

Classification Parameter Estimation and State Estimation


An Engineering Approach Using MATLAB 1st Edition Ferdinand
Van Der Heijden
https://ebookfinal.com/download/classification-parameter-estimation-
and-state-estimation-an-engineering-approach-using-matlab-1st-edition-
ferdinand-van-der-heijden/
ebookfinal.com
Introduction to MATLAB and SIMULINK A Project
Approach Third Edition Engineering Ottmar Beucher
Digital Instant Download
Author(s): Ottmar Beucher, Michael Weeks
ISBN(s): 9781934015049, 1934015040
Edition: 3rd
File Details: PDF, 3.63 MB
Year: 2007
Language: english
INTRODUCTION TO
MATLAB® & SIMULINK
A Project Approach
Third Edition
LICENSE, DISCLAIMER OF LIABILITY, AND LIMITED WARRANTY

The CD-ROM that accompanies this book may only be used on a single PC. This
license does not permit its use on the Internet or on a network (of any kind). By
purchasing or using this book/CD-ROM package(the “Work”), you agree that this
license grants permission to use the products contained herein, but does not give you
the right of ownership to any of the textual content in the book or ownership to any of
the information or products contained on the CD-ROM. Use of third party software
contained herein is limited to and subject to licensing terms for the respective
products, and permission must be obtained from the publisher or the owner of the
software in order to reproduce or network any portion of the textual material or
software (in any media) that is contained in the Work.

INFINITY SCIENCE PRESS LLC (“ISP” or “the Publisher”) and anyone involved in
the creation, writing or production of the accompanying algorithms, code, or
computer programs (“the software”) or any of the third party software contained on
the CD-ROM or any of the textual material in the book, cannot and do not warrant the
performance or results that might be obtained by using the software or contents of the
book. The authors, developers, and the publisher have used their best efforts to insure
the accuracy and functionality of the textual material and programs contained in this
package; we, however, make no warranty of any kind, express or implied, regarding
the performance of these contents or programs. The Work is sold “as is” without
warranty (except for defective materials used in manufacturing the disc or due to
faulty workmanship);

The authors, developers, and the publisher of any third party software, and anyone
involved in the composition, production, and manufacturing of this work will not be
liable for damages of any kind arising out of the use of (or the inability to use) the
algorithms, source code, computer programs, or textual material contained in this
publication. This includes, but is not limited to, loss of revenue or profit, or other
incidental, physical, or consequential damages arising out of the use of this Work.

The sole remedy in the event of a claim of any kind is expressly limited to replacement
of the book and/or the CD-ROM, and only at the discretion of the Publisher.

The use of “implied warranty” and certain “exclusions” vary from state to state, and
might not apply to the purchaser of this product.
INTRODUCTION TO
MATLAB® & SIMULINK
A Project Approach
Third Edition
O. BEUCHER
and
M. WEEKS

Infinity Science Press LLC


Hingham, Massachusetts
New Delhi
Revision & Reprint Copyright 2008 by Infinity Science Press LLC
All rights reserved.

Copyright © 2006 by Pearson Education Deutschland GmbH. All rights reserved.


First published in the German language under the title “MATLAB und Simulink” by
Pearson Studium, an imprint of Pearson Education Deutschland GmbH, München.

This publication, portions of it, or any accompanying software may not be reproduced in any way, stored in a retrieval
system of any type, or transmitted by any means or media, electronic or mechanical, including, but not limited to,
photocopy, recording, Internet postings or scanning, without prior permission in writing from the publisher.

Infinity Science Press LLC


11 Leavitt Street
Hingham, MA 02043
Tel. 877-266-5796 (toll free)
Fax 781-740-1677
[email protected]
www.infinitysciencepress.com

This book is printed on acid-free paper.

O. Beucher and M. Weeks. Introduction to MATLAB & Simulink: A Project Approach, Third Edition.
ISBN: 978-1-934015-04-9

The publisher recognizes and respects all marks used by companies, manufacturers, and developers as a means to
distinguish their products. All brand names and product names mentioned in this book are trademarks or service marks
of their respective companies. Any omission or misuse (of any kind) of service marks or trademarks, etc. is not an
attempt to infringe on the property of others.

Library of Congress Cataloging-in-Publication Data

Beucher, Ottmar. Introduction to MATLAB & SIMULINK : a project approach / Ottmar Beucher and Michael Weeks.
— 3rd ed.
p. cm.
Includes bibliographical references and index.
ISBN 978-1-934015-04-9 (hardcover with cd-rom : alk. paper)
1. Engineering mathematics–Data processing. 2. Computer simulation–Computer programs.
3. MATLAB. 4. SIMULINK. I. Weeks, Michael. II. Title.
TA345.B4822 2007
620.001’51–dc22
2007010556
Printed in the United States of America
7 8 9 4 3 2 1

Our titles are available for adoption, license or bulk purchase by institutions, corporations, etc. For additional
information, please contact the Customer Service Dept. at 877-266-5796 (toll free).

Requests for replacement of a defective CD-ROM must be accompanied by the original disc, your mailing address,
telephone number, date of purchase and purchase price. Please state the nature of the problem, and send the information
to Infinity Science Press, 11 Leavitt Street, Hingham, MA 02043.

The sole obligation of Infinity Science Press to the purchaser is to replace the disc, based on defective materials or
faulty workmanship, but not based on the operation or functionality of the product.
CONTENTS

Preface xv
Chapter 1. Introduction to MATLAB 1
1.1 What is MATLAB? 1
1.2 Elementary MATLAB Constructs 3
1.2.1 MATLAB Variables 4
1.2.2 Arithmetic Operations 13
1.2.3 Logical and Relational Operations 21
1.2.4 Mathematical Functions 26
1.2.5 Graphical Functions 33
1.2.6 I/O Operations 50
1.2.7 Import Wizard 52
1.2.8 Special I/O Functions 52
1.2.9 The MATLAB Search Path 54
1.2.10 Elementary Matrix Manipulations 56
1.3 More Complicated Data Structures 64
1.3.1 Structures 64
1.3.2 Cell Arrays 72
1.3.3 Definition of Cell Arrays 73
1.3.4 Access to Cell Array Elements 77
1.4 The MATLAB Desktop 82
1.5 MATLAB Help 86
1.6 MATLAB Programming 88
1.6.1 MATLAB Procedures 88
1.6.2 MATLAB Functions 90
1.6.3 MATLAB Language Constructs 95
1.6.4 The Function eval 107
1.6.5 Function Handles 109
1.6.6 Solution of Differential Equations 113

v
vi CONTENTS

1.7 MATLAB Editor and Debugger 123


1.7.1 Editor Functions 123
1.7.2 Debugging Functions 125
1.8 Symbolic Calculations With The Symbolics Toolbox 127
1.8.1 Symbolic “Auxiliary Calculations” 131
Chapter 2. Introduction to Simulink 135
2.1 What is SIMULINK? 135
2.2 Operating Principle And Management of Simulink 136
2.2.1 Constructing a Simulink Block Diagram 138
2.2.2 Parametrizing Simulink Blocks 141
2.2.3 Simulink Simulation 145
2.3 Solving Differential Equations with Simulink 150
2.4 Simplification of Simulink Systems 159
2.4.1 The Fcn Block 159
2.4.2 Construction of Subsystems 160
2.5 Interaction with MATLAB 164
2.5.1 Transfer of Variables between
Simulink and MATLAB 164
2.5.2 Iteration of Simulink Simulations in MATLAB 167
2.5.3 Transfer of Variables Through Global Variables 179
2.6 Dealing with Characteristic Curves 180
Chapter 3. Projects 189
3.1 Hello World 189
3.1.1 Personalized Hello World 189
3.1.2 Hello World with Input 190
3.2 Simple Menu 191
3.3 File Reading and Writing 195
3.3.1 Writing a File 195
3.3.2 Reading a File 196
3.4 Sorting 199
3.5 Working with Biological Images 202
3.5.1 Creating a Sub-image 203
3.5.2 Working with Multiple Images 208
3.6 Working with a Sound File 210
3.7 Permutations 217
3.8 Approaching a Problem and Using Heuristics 222
3.9 Making Permutations Faster 223
3.9.1 A Faster Way 223
CONTENTS vii

3.9.2 Measuring Time 226


3.9.3 The Growth of the Problem 228
3.10 Search a File 229
3.10.1 A Side Note About System Commands 229
3.10.2 DNA Matching 230
3.10.3 Our Search Through a File 231
3.10.4 Buffering Our Data 234
3.10.5 A Further Check 239
3.10.6 Generating Random Data 244
3.11 Analyzing a Car Stereo 247
3.11.1 A Fun Sound Effect 254
3.11.2 Another Fun Sound Effect 255
3.11.3 Why Divide By 2? 256
3.11.4 Stereo Test Conclusion 259
3.12 Drawing a Line 262
3.12.1 Finding Points Along a Line 262
3.12.2 Coding the Solution to Points Along a Line 264
3.12.3 Drawing the Line 267
3.13 Drawing a Frame 269
3.14 Filling a Diamond Shape 273
3.15 Drawing an Entire Cube 278
3.16 Adjusting Our View 282
3.17 Epilogue 287
Chapter 4. Solutions to the Problems 289
4.1 Solutions to the MATLAB Problems 289
4.2 Solutions to the Simulink Problems 349
Appendix A. Table of Arithmetic MATLAB Operations 367
A.1 Arithmetic Operations as Matrix Operations 367
A.2 Arithmetic Operations as Field Operations 369
Appendix B. About the CD-ROM 371
Appendix C. New Release Information (R2007b) 373
C.1 Backwards Compatibility 373
C.2 What is New for R2007b 375

Software Index 377


Index 381
LIST OF FIGURES

1.1 The MATLAB command interface 4


1.2 The workspace browser 8
1.3 Representation of a matrix in the array editor 8
1.4 A MATLAB example of a simple x, y plot 35
1.5 The x, y plot with a different “line style.” 36
1.6 x, y plot with multiple functions 37
1.7 x, y plot with multiple functions and different line colors and styles 37
1.8 x, y plot using the stem plot function 38
1.9 x, y plot using the stairs function 39
1.10 A labelled x, y plot using the plot function 40
1.11 A segment of Fig. 1.10 using the “axis” command 40
1.12 The MATLAB plot window with a sample graph 41
1.13 The plot-tools window 43
1.14 A three-dimensional plot using the mesh command 44
1.15 A three-dimensional plot using the surf command 45
1.16 A three-dimensional plot using the contour3 command 46
1.17 A graph with two plots using the subplot command 47
1.18 The import wizard 52
1.19 Visualization of the cell array measurements with cellplot 76
1.20 Visualization of the cell array measurements with cellplot 77
1.21 Shortcut toolbar with the self-defined shortcut “clear screen” 83
1.22 Context menu in the command-history window 84
1.23 Tab-completion function 85
1.24 The MATLAB help window after a search operation 87
1.25 The mathematical pendulum 115
1.26 Solution of Eq. (1.4) with MATLAB’s ode23 117
1.27 RC combination with a voltage source 119
1.28 Step function response of the RC combination for 10 k and 4.7 µF 121
1.29 Editor-debugger with the pendde.m file open 124

ix
x LIST OF FIGURES

1.30 Editor-debugger with the pendde.m file open, a breakpoint and


the displayed variable content 126
1.31 Rectified sine wave and the RMS equivalent voltage 131
2.1 Block diagram representation of a dynamic system 136
2.2 Simulink library browser (foreground) and the opened Simulink
function library Sources (background) 137
2.3 The Simulink system s_test1 after insertion of the
Sine Wave-Block 138
2.4 The Simulink system s_test1 after insertion of the
Sine Wave-Block and the Integrator-Block 139
2.5 The (almost) ready Simulink system s_test1 140
2.6 The parameter window for the Simulink block Mux 141
2.7 The parameter window for the Simulink block
Sine Wave (Source signal) 142
2.8 Display window for the Simulink block Scope with an open
Parameters window 143
2.9 The completed Simulink system s_test1 145
2.10 The Configuration Parameters (simulation parameter) window 146
2.11 The result of the sample simulation 148
2.12 The result of the sample simulation after processing by MATLAB 149
2.13 The technique for integrating to find y(t) 151
2.14 The Simulink system for solving Eq. (2.3) 152
2.15 The parameter window for the Simulink system of Fig. 2.14 152
2.16 The Simulink system s_logde for solving a logistic differential
equation 153
2.17 A Simulink solution of the logistic differential equation 154
2.18 Mechanical oscillator (steel plate) 155
2.19 A Simulink system for solving Eq. (2.12) 157
2.20 Simulink solution of Eq. (2.12) 158
2.21 The Simulink system s_logde2 with an Fcn block 160
2.22 Selecting the blocks that will be assembled into a subsystem 161
2.23 The system s_logde after creation of the subsystem
(file s_Logde3.m) 162
2.24 Structure of the subsystem s_Logde3.m 162
2.25 The system s_Logde3 with the model browser activated 163
2.26 The Simulink system s_denon2 for solving Eq. (2.12) with
common parameters from the MATLAB workspace 167
2.27 The configuration parameters window for Simulink system s_denon2 168
2.28 The Simulink system s_denon3 172
LIST OF FIGURES xi

2.29 Results of the iterated execution of the simulation system s_deno3


using denonit for three different plate radii 178
2.30 The lookup table block from the lookup tables block set
with the block parameter window for lookup table 181
2.31 Voltage-current characteristic of a solar cell 182
2.32 The Simulink system s_charc with a Lookup Table for
determining the operating point of a solar cell 183
2.33 The Simulink system s_charc2 with a Lookup Table for
determining the optimum operating point of a solar cell 185
2.34 Resistance-power characteristic for a solar cell 186
3.1 An example graphical menu 192
3.2 An idealized example image of C. elegans worms 203
3.3 Four possibilities for selecting two corner points 207
3.4 Frequency magnitudes for the entire violin recording 211
3.5 Walking 3 units east and 4 units north reaches the same destination
as turning 53.1 degrees and walking 5 units 213
3.6 A typical spectral plot of the violin recording 215
3.7 Example DNA data 231
3.8 A typical stereo speaker 251
3.9 Spectrum from the sweep function 255
3.10 Drawing lines on an image 269
3.11 A frame outline of a cube 272
3.12 A typical diamond shape to fill 276
3.13 The lines on the left give us two possibilities for a column coordinate 277
3.14 Black diamond shape on a white background 278
3.15 Black rectangle on a white background 278
3.16 Frame showing the vertex points on each face 284
3.17 Frame showing the vertex points on each face, flipped 284
3.18 How flipping the cube affects one face 286
4.1 The Array Editor with the matrix V before filling row 5 with zeroes 292
4.2 Graphical result of solwhatplot 308
4.3 Representing the cell array sayings with cellplot 327
4.4 Comparing the solutions of the linearized and nonlinear differential
equations for a mathematical pendulum with a large initial deviation 338
4.5 Response to excitation of the RC low pass filter in the example by
two different oscillations 340
4.6 Solutions of the differential equation for the mathematical pendulum
for pendulums of length 5 and 20 342
xii LIST OF FIGURES

4.7 Solution of the system of differential equations from Problem 78.


Top: numerical solution with ode23, bottom: symbolic solution
using dsolve 344
4.8 Simulink system for solving u̇(t) = −2 · u(t) 350
4.9 Detail from the Simulink system s_solOscill 351
4.10 Simulink system s_solpendul for solving the (unlinearized)
differential equation for the mathematical pendulum 352
4.11 Simulink system for solving the initial value problem, Eq. (2.13) 352
4.12 Simulink system for solving the initial value problem (2.14) 353
4.13 Simulink system for solving the system of differential equations (2.15) 354
4.14 Simulink system for solving Eq. (2.12) 356
4.15 Simulink system for solving the system of differential equations (2.15) 357
4.16 The system s_denon5.mdl 357
4.17 Simulink system for solving the initial value problem (2.17) 361
4.18 Simulink system for simulation of the characteristic curve (2.21) 364
4.19 Simulation of s_solcharc with amp=1, 2, and 5 365
4.20 Simulink system for simulating the family of characteristic curves (2.22) 366
LIST OF TABLES

3.1 Run times (seconds) for the original and improved “perm” functions 226
3.2 Run times (seconds) for the original “perm” function,
on two different computers 228
3.3 Run time comparisons (seconds) 240

xiii
PREFACE

T
his book is primarily intended for first semester engineering students who are
looking for an introduction to the MATLAB and Simulink environment ori-
ented toward the knowledge and requirements of beginning students. Thus,
only a few basic ideas from mathematics, in particular ordinary differential equa-
tions, programming, and physics are required to understand the contents of this
book. This knowledge is usually acquired in the first two or three semesters of a
technical engineering degree program.
Under these conditions, this book should also be of interest for practicing engi-
neers who are looking for a brief introduction to MATLAB and Simulink. In the case
of this book, engineers will have the knowledge required to understand it years after
they have finished their studies.
The MathWorks periodically updates MATLAB and Simulink software. See
Appendix C for information about R2007b, the release made in September, 2007.
The examples in this book are compatible with the new version.

THE LAYOUT OF THIS BOOK

The first chapter covers the basic principles of MATLAB. It explains the fundamental
concepts, how to handle the most important commands and operations, and the basics
of MATLAB as a programming language. This chapter, like Chapter 2, emphasizes
the numerical solution of ordinary differential equations. Beyond this, there are some
comments on the symbolics toolbox, which makes the core of the computer algebra
program MAPLE available to the MATLAB user and, thereby, enables symbolic
calculations in MATLAB.
Chapter 2 is an introduction to the use of Simulink. Here the emphasis is on the
solution of ordinary differential equations or systems of differential equations and,
with that, the simulation of dynamic systems. Particular attention is paid to the various
techniques for interaction between MATLAB and Simulink. Thus, for example, it is
shown how the execution of Simulink simulations can be automated in MATLAB.

xv
xvi PREFACE

Both Chapters 1 and 2 are supplemented by a large number of problems which


are set up so that they can be worked out by readers as they proceed, before starting
the next section of the book. The problems are an integral component of the sections
and should definitely be worked out independently on a computer right away, because
this is the only way to master the subject matter.
Chapter 3 adds a set of programming projects. These are modeled from real-
world problems, and go into greater depth than the earlier practice problems. Each
section presents a task to be accomplished, then walks the reader through any back-
ground information and the solution. The MATLAB code for these projects can be
found on the CD-ROM.
In Chapter 4 the problems posed in the first two chapters are provided with
complete solutions. All the solutions, along with the sample programs discussed in
these chapters, are included as files in the accompanying software, so that the reader’s
own computer solutions of the problems can always be checked.
N
TH E C
The CD-ROM contains source code for the MATLAB problems and projects, as well
D
O

as Simulink model files. The sound files generated in Chapter 3 are stored on the
CD-ROM under the folder sweep_data. It also contains images from the book.
Hence, the book is also suitable for self study.

COMMENTS ON THE THIRD EDITION

There are many changes in the new working interface of MATLAB and Simulink.
And, naturally, the corresponding discussion has had to be modified. The most
important content changes are in the sections on cell arrays and function handles.
To be sure, cell arrays showed up in the earlier MATLAB versions, but these
data structures were not mentioned in the two earlier editions. In the meantime, I
have been persuaded to refer to this very flexible tool, even though dealing with these
data structures might still be difficult for the beginner. In many cases, however, cell
arrays cannot be avoided, so at least the essentials should be discussed thoroughly.
Function handles also showed up earlier. But the concept of calling is new. This
makes using the function feval superfluous and makes the call natural. This is also
discussed in a short section.
Other innovations have not been included, since they go beyond the scope of a
basic introduction.
All the new topics have again been supplemented with corresponding problems.
Thus, the number of problems (as ever, fully solved) now exceeds 100.
Chapter 3 is also a new addition, with in-depth programming projects.
PREFACE xvii

In sum, the third edition gives the reader has a fully-up-to-date introduction to
the current versions of MATLAB and Simulink.

REMARKS ON NOTATION

In this book, MATLAB code is generally set in typewriter font. The same holds
for MATLAB commands belonging to the built-in MATLAB environment, such as
the commands whos or the function ode23.
MATLAB commands based on the programs written by the authors are also set
in typewriter font, e.g., the command FInput.
Simulink systems belonging to the built-in environment, such as the parameters
of Simulink systems, are also generally set in typewriter font, e.g., the parameter
Amplitude of the Simulink block Sine Wave.
The names of Simulink systems provided by the author always begin with an
s_. This is of historical origin. Before MATLAB 5, MATLAB programs and Simulink
systems were m files. Since Simulink systems after MATLAB 5 have the ending *.mdl,
it was basically no longer necessary to distinguish them by putting an s_ in front. But,
a second indication of the difference cannot hurt, so this naming convention has been
retained.
Metanames, i.e., names in commands, which are to be replaced by the actual
name in calls, are set in <...> . The formulation help <command name> thus
means that on calling, the entry <command name> must be replaced by the actual
command about which help is being sought. Here the angle brackets do not have to
be entered.
The names of the accompanying programs are accentuated in typewriter
font in the text. There is, of course, much more extensive comment in the programs
than in the printed excerpts. This is particularly so for the solutions to the problems
which have been shortened for reasons of space.
In order to make it easier for the reader to find the programs in the text, an index
of the accompanying software is given at the end of the book.

ACKNOWLEDGMENTS

First of all, thanks to my colleagues Helmut Scherf and Josef Hoffmann for their
many comments and discussions on this topic.
I also thank the students in the Automotive Technology major in the Department
of Mechatronics, who served as “guinea pigs” in some of the one-week compact
courses that preceded the development of this book. Naturally, the (known and
xviii PREFACE

unknown) reactions of the students had a great influence on the development of this
book. I thank Dietmar Moritz, as a representative of them all, for some valuable
comments which have been directly incorporated into the book.
O.B., Lingenfeld and Karlsruhe, Germany, 2007

Thanks to the American Institute of Physics, who performed the translation.


I appreciate the support of my students at Georgia State University, especially
those who used MATLAB in my Digitial Signal Processing and Introduction to
MATLAB Programming classes.
Thanks to Laurel Haislip for playing the violin for the example sound file. I regret
that I could only share 17 seconds of your music with the world.
Finally, I would like to acknowledge the support of my wife, Sophie.
M.C.W., Atlanta, Georgia, USA, 2007
Chapter 1 INTRODUCTION
TO MATLAB

T
his chapter presents the fundamental properties and capabilities of
the computational and simulation tool MATLAB.

The purpose of this chapter is to introduce beginners to MATLAB and


familiarize them with the basis structure of this software. To make this intro-
duction more accessible, only a few elementary mathematical concepts from
linear algebra (vector and matrix calculations) and the analysis of elementary
functions will be assumed.
At this point we will avoid more advanced concepts, especially those pro-
vided by the MATLAB function libraries (the so-called toolboxes), since they
require more extensive knowledge of mathematics, signal processing, control
technology, and many other disciplines, and are therefore inappropriate for
the beginning students for whom this introduction is intended.

1.1 WHAT IS MATLAB?

MATLAB is a numerical computation and simulation tool that was developed


into a commercial tool with a user friendly interface from the numerical
function libraries LINPACK and EISPACK, which were originally written
in the FORTRAN programming language.
As opposed to the well-known computer algebra programs, such as
MAPLE or MATHEMATICA, which are capable of performing symbolic
operations and, therefore, calculating with mathematical equations as a per-
son would normally do with paper and pencil, in principle MATLAB does
purely numerical calculations. Nevertheless, computer algebra functionality
can be achieved within the MATLAB environment using the so-called “sym-
bolics” toolbox. This capability is a permanent component of MATLAB 7 and
is also provided in the student version of MATLAB 7. It involves an adaptation
of MAPLE to the MATLAB language. We shall examine this functionality in
Section 1.8.

1
2 INTRODUCTION TO MATLAB & SIMULINK

Computer algebra programs require complex data structures that involve


complicated syntax for the ordinary user and complex programs for the pro-
grammer. MATLAB, on the other hand, essentially only involves a single
data structure, upon which all its operations are based. This is the numerical
field, or, in other words, the matrix. This is reflected in the name: MATLAB
is an abbreviation for MATrix LABoratory.
As MATLAB developed, this principle gradually led to a universal pro-
gramming language. In MATLAB 7 far more complex data structures can be
defined, such as the data structure structure, which is similar to the data
structure struct of the C++ programming language, or from the so-called
cell arrays to the definition of classes in object oriented programming.1
Except for structures and cell arrays, which we discuss in Sections 1.3.1
and 1.3.2, in this elementary introduction we will not consider the more
advanced capabilities of MATLAB programming, such as object oriented
programming and defining certain classes. This would require an extensive
background in programming beyond the scope of the present introduction.
If one limits oneself to the basic data structure of the matrix, then
MATLAB syntax remains very simple and MATLAB programs can be writ-
ten far more easily than programs in other high level languages or computer
algebra programs. A command interface created for interactive management
without much ado, plus a simple integration of particular functions, pro-
grams, and libraries supports the operation of this software tool. This also
makes it possible to learn MATLAB rapidly.
As we have already noted, MATLAB is not just a numerical tool for evalu-
ation of formulas, but is also an independent programming language capable
of treating complex problems and is equipped with all the essential constructs
of a higher programming language. Since the MATLAB command interface
involves a so-called interpreter and MATLAB is an interpreter language, all
commands can be carried out directly. This makes the testing of particular
programs much easier.
Beyond this, MATLAB 7 is also equipped with a very well conceived
editor with debugging functionality (Section 1.7), which makes the writing
and error analysis of large MATLAB programs even easier.
The last major advantage is the interaction with the special toolbox
Simulink, which we shall introduce in Chapter 2. This is a tool for constructing
simulation programs based on a graphical interface in a way similar to block

1
All data structures (there are 15 different kinds of them) can usually be subsumed
under the concept of a “field” (array). Thus, MATLAB yields ARRLAB (ARRay
LABoratory). From this concept it follows that the numerical field and, therefore,
the classical matrix, is essentially just a special case.
INTRODUCTION TO MATLAB 3

diagrams. The simulation runs under MATLAB and an easy interconnection


between MATLAB and Simulink is ensured. In Chapter 2 we shall discuss
these and other properties of Simulink in detail.

1.2 ELEMENTARY MATLAB CONSTRUCTS

Starting with the basic data structure of the numerical field, the most impor-
tant elementary constructs and operations of MATLAB (in the author’s
opinion) will be presented here. Initially, MATLAB will only be used
interactively. It will be shown how (numerical) calculations are carried out
interactively and how the results of these calculations can be represented
graphically and checked.
The elementary MATLAB operations can be divided roughly into five
classes:

 Arithmetic operations
 Logical operations
 Mathematical functions
 Graphical functions
 I/O operations (data transfer)

In essence, all these operations involve operations on matrices and vectors.


These in turn are kept as variables which, with very few restrictions, can be
defined freely in the MATLAB command interface.
The MATLAB command interface shows up at the start of MATLAB in
the form shown in Fig. 1.1 or something similar.2
The main elements of this command interface are:

1. the command window,


2. the command-history window,
3. the current directory window or (hidden in this view) the workspace
(variable window),
4. the file information window,
5. the icon toolbar with the choice menu for the current directory,
6. the shortcut toolbar, and
7. the start button.

2
This depends on the user’s settings. These settings can be specified in the menu
command File - Preferences.
4 INTRODUCTION TO MATLAB & SIMULINK

FIGURE 1.1 The MATLAB command interface.

The function of the individual elements will be discussed later, in the


relevant sections. At present, only the command window, which displays the
most important user interface during interactive operation, is of significance.
In the command window (1) MATLAB awaits the user’s commands,
which are to be directly interpreted and executed by MATLAB following an
input prompt >> (in the student version EDU>>). Thus, the user normally
communicates with the MATLAB system interactively. We shall deal with
the possibility of programming in MATLAB in Section 1.6.
Before proceeding to the details of the individual operational classes, the
concept of MATLAB variables should be explained further. In doing so, we
shall also point out some peculiarities of MATLAB syntax and the interaction
with the MATLAB command interface.

1.2.1 MATLAB Variables


A MATLAB variable is an object belonging to a specific data type. As noted
at the beginning, the most basic data type is one from which MATLAB takes
its name, the matrix. For the sake of simplicity, from here on a MATLAB
INTRODUCTION TO MATLAB 5

variable is basically a matrix. Matrices can be made up of real or complex


numbers, as well as characters (ASCII symbols). The latter case is of interest
in connection with the processing of strings (text). But for now we’ll postpone
that discussion.

Defining MATLAB Variables


In general, the matrix is defined in the MATLAB command interface by input
from the keyboard and assigned a freely chosen variable name in accordance
with the following syntax:
>> x = 2.45

With this instruction, after a MATLAB prompt the number 2.45 (a num-
ber is a 1 × 1 matrix!) will be assigned to the variable x and can subsequently
be addressed under this variable name.
MATLAB responds to this definition with
x =

2.4500

and, in the interactive mode, confirms the input. An error message appears
if there are any errors of syntax.
Numbers are always represented by 4 digits after the decimal point
by default (format short). The default can be changed in the menu
command File - Preferences ... under the listing Command -
Window - Numeric Format. In most cases, however, the default
representation is the best choice.
The following commands define a row vector of length 3 and a 2 × 3
matrix. The response of MATLAB is also shown for each case:
>> vector = [1 5 -3]

vector =

1 5 -3

>> thematrix = [3 1+2*i 2; 4 0 -5]

thematrix =

3.0000 1.0000 + 2.0000i 2.0000


4.0000 0 -5.0000
6 INTRODUCTION TO MATLAB & SIMULINK

Note that the matrix thematrix contains a complex number as an ele-


ment. Complex numbers can be defined this way in the algebraic rep-
resentation using the symbols i and j that have been reserved for this
purpose. Therefore, if possible, these symbols should not be used for other
variables.
As the above example shows, the delimiters for the entries in the
columns of the matrix are spaces (or, alternatively, commas) and the rows
are delimited by semicolons. A column vector can, therefore, be defined as
follows:
>> colvector = [2; 4; 3; -1; 1-4*j]

colvector =

2.0000
4.0000
3.0000
-1.0000
1.0000 - 4.0000i

If no variable name is set, MATLAB assigns the name ans (answer) to the
result, as the following example shows:
>> [2,3,4; 3,-1,0]

ans =

2 3 4
3 -1 0

The Workspace
All of the defined variables will be stored in the so-called workspace of MAT-
LAB. You can check the state of the workspace at any time. The command
who returns the names of the saved variables and the command whos pro-
vides additional, perhaps vital, information, such as the dimension of a matrix
or the memory allocation.
This command yields the following for the preceding examples:
>> who

Your variables are:

ans colvector thematrix vector x


INTRODUCTION TO MATLAB 7

>> whos
Name Size Bytes Class

ans 2x3 48 double array


colvector 5x1 80 double array (complex)
thematrix 2x3 96 double array (complex)
vector 1x3 24 double array
x 1x1 8 double array

Grand total is 21 elements using 256 bytes

A very practical way of getting an overview of the content of the


workspace is provided by the workspace browser, which can be selected using
the menu command Desktop - Workspace. In Fig. 1.1 the workspace
browser has already been opened and is firmly docked in the command inter-
face. In this configuration the workspace is hidden by the window of the
current listing (3, 4), but it can be brought into the foreground by clicking
the corresponding icon. With a click on the arrow in the menu, you can
“undock”3 the window from its dock in the command interface. This docking
mechanism can also be applied to all the windows. The extent to which this
is used depends on the user’s taste.
Fig. 1.2 shows how the workspace browser displays the instructions
specified above in its undocked state.
A double click on a variable opens the array editor and displays the
contents of the variables in the style of a Microsoft Excel Table (Fig. 1.3).
Multiple variables can be selected simultaneously (by holding down the con-
trol key and clicking) and then the toolbar can be opened with the open
selection button.4
The dimensions of the matrices, the display format, and the individual
entries for the matrices can be changed in the array editor. This is especially
useful for large matrices, which cannot be viewed in the command window
(as in Problem 6). Entire columns or rows can even be copied, erased, or
added. In this way it is very easy, for example, to exchange data between Excel
and the array editor (and, thereby, to MATLAB) manually with the aid of

3
This action toggles the docking function, and can be used to dock the window there
again.
4
The significance of the button is most easily understood by bringing the mouse
pointer over the button and holding it there for a moment. This opens up a text
window with the name of the button.
8 INTRODUCTION TO MATLAB & SIMULINK

FIGURE 1.2 The workspace browser.

FIGURE 1.3 Representation of a matrix in the array editor.

the standard Windows copy-paste mechanism in the Windows platform


(Problem 6).
If some variables are no longer needed, it is easiest to erase them with
the command clear in the command interface. For example,
>> clear thematrix

yields
>> who

Your variables are:

ans colvector vector x


INTRODUCTION TO MATLAB 9

or the erasure of thematrix. The entire workspace is erased using


clear or clear all. These operations are also possible in the workspace
browser.

Reconstructing Commands
The commands that have been set previously are saved. In this way you
can conveniently repeat or modify a command. For this only the arrow
keys ↑ and ↓ have to be pressed. The earlier commands show up in the
MATLAB command window and can (if necessary, after modification) be
brought up again using the return key. For instance, the definition of the
recently erased matrix thematrix can be recovered and reconstructed in
this way.
In long MATLAB sessions this keying through earlier commands
becomes rather tedious. If you know the first letters of the command, you
can shorten the search. Thus, for example, to find the matrix thematrix
you need only type
>> them

and then press the arrow key ↑. Only commands beginning with them
will be searched for. If the beginning is unique, the command is found at
once.
Other convenient possibilities employing the so-called history-
mechanism are provided by the command-history window.
In Fig. 1.1 this command-history window (2) can be seen at the lower
left. In this window the commands set in the past are listed under the cor-
responding date of the MATLAB session. By scrolling, it is also very easy
to find commands from even further back. A double click on the command
is sufficient to activate it again. Some other application possibilities will be
discussed in Section 1.4.
The choice of command reconstruction capabilities ultimately depends
on the preference of the user and practical considerations.

Other Possibilities for Defining Variables


The problem often arises of expanding a matrix or vector by adding extra
components or of eliminating columns and rows.
An expansion can be done in the way described above by adding to the
variable name. Thus, the matrix thematrix can be expanded by an extra
row using the following command:
>> thematrix = [thematrix; 1 2 3]
10 INTRODUCTION TO MATLAB & SIMULINK

thematrix =

3.0000 1.0000 + 2.0000i 2.0000


4.0000 0 -5.0000
1.0000 2.0000 3.0000

Another column could be added using the following command:


>> thematrix = [thematrix, [1;2;3]]

thematrix =

3.0000 1.0000 + 2.0000i 2.0000 1.0000


4.0000 0 -5.0000 2.0000
1.0000 2.0000 3.0000 3.0000

or with
>> v = [1;2;3]

v =

1
2
3

>> thematrix = [thematrix, v]

thematrix =

3.0000 1.0000 + 2.0000i 2.0000 1.0000


4.0000 0 -5.0000 2.0000
1.0000 2.0000 3.0000 3.0000

If you want to delete the second column, then you must fill it with an empty
vector [ ]. The second column in the variable thematrix will then be
addressed in accordance with the conventional matrix indexing. Since the
row index is arbitrary in this case, it is indicated by the place holder : (colon).
This yields
>> thematrix(:,2) = []

thematrix =

3 2 1
4 -5 2
INTRODUCTION TO MATLAB 11

1 3 3

The first row can thus be deleted using


>> thematrix(1,:) =[]

thematrix =

4 -5 2
1 3 3

Likewise, a row or column vector can be selected and another variable can
be assigned. Thus, with
>> firstrow = thematrix(1,:)

firstrow =

4 -5 2

the first row of the remaining residual matrix is selected.


Rather than carrying out specified commands in the command window,
the operations described above can, of course, also be performed within the
array editor. However, with a little practice, working in the command plane
is significantly faster. In addition, these operations can also be applied within
MATLAB programs; that is, in a noninteractive mode (Section 1.6). They are
then the only way of obtaining the desired results. Thus, these techniques are
of great importance for using the functionality of MATLAB as a programming
language.
When it is necessary to process large matrices or vectors, outputting the
results is often very inconvenient. An example is the following definition of
a vector consisting of the numbers from 1 to 5000 in steps of 2. It can be
defined simply in MATLAB by the following command, which specifies the
starting value, step size, and final value:
>> largevector = (0:2:5000)

largevector =

Columns 1 through 12

0 2 4 6 8 10 12 14 16 ...

Columns 13 through 24

24 26 28 30 etc.
12 INTRODUCTION TO MATLAB & SIMULINK

Of course, the vector is not displayed here in full.


In order to suppress the output of a MATLAB calculation, the command
must be ended with a semicolon. The statement
>> largevector = (0:2:5000);

lets MATLAB proceed without response in the above case.


If it is desired not to suppress the MATLAB answer entirely, but to show
the result on the screen, the command
>> more on

will let the output in the full command window be suspended when the user
ends the execution of the screen display by pressing a key. This function then
enables the further progress of the interactive MATLAB session. But it can
also be shut off again by entering
>> more off

as a command.

PROBLEMS

All the important constructs for defining MATLAB variables have now been
brought together in order to begin with the first problems on this subject.
NOTE Solutions to all problems can be found in Chapter 4.

Problem 1
Define the following matrices or vectors according to MATLAB and
classify the corresponding variables:
 
1 0 0
M = 0 j 1 ,
j j + 1 −3
k = 2.75 ,
 
1
 3
v = 
 −7 ,

−0,5
 
 = 1 −5.5 −1.7 −1.5 3 −10.7 ,
w
 
y = 1 1.5 2 2.5 · · · 100.5 .
INTRODUCTION TO MATLAB 13

Problem 2
1. Expand the matrix M to a 6 × 6 matrix V of the form

M M
V= .
M M

2. Delete row 2 and column 3 from the matrix V (reduced matrix V23).
3. Create a new vector z4 from row 4 of the matrix V.
4. Modify the entry V(4, 2) in the matrix V to j + 5.

Problem 3
From the vector
 
r = j j + 1 j − 7 j+1 −3
construct a matrix N consisting of 6 columns where each contain r.
Problem 4
Check whether the row vector of Problem 3 can be joined onto the matrix N
that was constructed there.
Problem 5
Erase all variables from the workspace and reconstruct the matrix V of
Problem 2 using the saved commands and the ↑ and ↓ keys.
Carry out the same procedure once again with the aid of the command-
history window.
Problem 6
Fill row 5 of the matrix V of Problem 2 with zeroes using the array editor.
Problem 7
Open the file ExcelDatEx.xls of the accompanying software in Microsoft
Excel. Transfer the data contained in it to the array editor using the Windows
interface.
Next, delete the second column of the transferred data matrix in the
MATLAB command window and then copy it back into Excel via the
Windows interface.

1.2.2 Arithmetic Operations


The arithmetic operations (+, −, ∗, etc.) in MATLAB have an important
characteristic to which the beginner must become accustomed early on.
14 INTRODUCTION TO MATLAB & SIMULINK

Matrix Operations
Since the fundamental data structure of MATLAB is the matrix, these oper-
ations must, above all, be understood as matrix operations. This means that
the computational rules of matrix algebra are assumed, with all the associated
consequences.
Thus, for example, the product of two variables A and B is not defined
according to MATLAB if the underlying matrix product A · B is not defined;
that is, if the number of columns in A is not equal to the number of rows in B.
An exception to this rule occurs only if one of the variables is a 1 × 1
matrix, or scalar. Then the multiplication is interpreted as multiplication by
a scalar in accordance with the rules of linear algebra.
The following examples of MATLAB commands5 will make this clearer:
>> M = [1 2 3; 4 -1 2] % define 2x3-Matrix M

M =

1 2 3
4 -1 2

>> N = [1 2 -1 ; 4 -1 1; 2 0 1] % define 3x3-Matrix N

N =

1 2 -1
4 -1 1
2 0 1

>> V = M*N % trying the product M*N

V =

15 0 4
4 9 -3

>> W = N*M % trying the product N*M


??? Error using ==> mtimes
Inner matrix dimensions must agree.

5
Comments can be introduced after commands using the % symbol. Later on, this
will be very useful in writing MATLAB programs. The characters after % in a line
will be ignored by MATLAB.
INTRODUCTION TO MATLAB 15

Thus, MATLAB responds to the attempt to multiply the 2 × 3 matrix M


by the 3 × 3 matrix N with the 2 × 3 product matrix V. The attempt
to switch the factors fails, since the product of a 3 × 3 matrix and a
2 × 3 matrix is not defined. MATLAB quits this with the error message
inner matrix dimensions must agree, which even experienced
MATLAB programmers will encounter again and again.

Field Operations
Besides the matrix operations, in many cases there is a need for corre-
sponding arithmetic operations, which must be carried out term-by-term
(componentwise).
Operations that are to be understood as term-by-term, which are known
as field operations or array operations in MATLAB, must at the very least be
given a new notation as they might otherwise be confused with matrix oper-
ations. This is solved in MATLAB syntax by placing a period (.) before the
operator symbol. An * alone, therefore, always denotes matrix multiplication,
while a .* always denotes term-by-term multiplication (array multiplica-
tion). This leads to other rules about the dimensionality of the objects, as the
following example shows:

>> M = [1 2 3; 4 -1 2] % define 2x3-Matrix M

M =

1 2 3
4 -1 2

>> N = [1 -1 0; 2 1 -1] % define 2x3-Matrix N

N =

1 -1 0
2 1 -1

>> M*N % Matrix product M*N


??? Error using ==> mtimes
Inner matrix dimensions must agree.

>> M.*N % term-by-term multiplication


16 INTRODUCTION TO MATLAB & SIMULINK

ans =

1 -2 0
8 -1 -2

As you can see, the matrix product M*N is not defined this time.
Instead, the product is defined term-by-term. To each entry in M there is
a corresponding entry in N, with which the product can be formed.
Another common example is the squaring of the components of a vector:
>> vect = [ 1, -2, 3, -2, 0, 4]

vect =

1 -2 3 -2 0 4

>> vect^2 % squaring the vector vect


??? Error using ==> mpower
Matrix must be square.

>> vect.^2 % vect-squared, term-by-term

ans =

1 4 9 4 0 16

In the first case MATLAB could again carry out a matrix operation. Squaring
a matrix, however, is only possible if the matrix is square (i.e., it has the same
numbers of columns and rows) which is not so here. But, the components
themselves can be squared in any case.

Division Operations
The division sign has special significance. In MATLAB we distinguish
between right division / and left division \.
The fact that there are two division operations is again a consequence of
the matrix algebra interpretation. Division of two matrices A and B (i.e., A/B)
is normally not defined. In the case of square matrices, the quotient can only
be interpreted meaningfully as X = A · B−1 if the inverse matrix B−1 exists.
If A−1 exists, then “left division” X = A\B is also meaningful, interpreted in
this case as X = A−1 · B.
MATLAB takes these two situations into account by defining left and
right division. Let us clarify this with a simple example involving two
INTRODUCTION TO MATLAB 17

invertable 2 × 2 matrices.

>> A = [2 1 ;1 1] % Matrix A

A =

2 1
1 1

>> B = [- 1 1;1 1] % Matrix B

B =

-1 1
1 1

>> Ainv = [1 -1; -1, 2] % inverse of A

Ainv =

1 -1
-1 2

>> Binv = [-1/2 1/2; 1/2, 1/2] % inverse of B

Binv =

-0.5000 0.5000
0.5000 0.5000

>> X1 = A/B % right division

X1 =

-0.5000 1.5000
0 1.0000

>> X2 = A*Binv % checking

X2 =

-0.5000 1.5000
0 1.0000
18 INTRODUCTION TO MATLAB & SIMULINK

>> Y1 = A\B % left division

Y1 =

-2.0000 -0.0000
3.0000 1.0000

>> Y2 = Ainv*B % checking

Y2 =

-2 0
3 1

The next example shows, however, that MATLAB goes one step further in
the interpretation of the division operations:
>> A = [2 1 ;1 1] % Matrix A

A =

2 1
1 1

>> b=[2; 1] % column vector b

b =

2
1

>> x = A\b % left division of A "by" b

x =

1.0000
0.0000

>> y = A/b % right division of A "by" b


??? Error using ==> mrdivide
Matrix dimensions must agree.
INTRODUCTION TO MATLAB 19

 obviously yields a solution (in this case unique)


Here “left division,” x = A\b,
 as the following test shows:
of the linear system of equations Ax = b,
>> A*x

ans =

2.0000
1.0000

The right division is not defined.


Left and right division can also be used with nonsquare matrices for
solving under- and over-determined systems of equations. But since these
applications require more extensive mathematical knowledge than can or
should be assumed here, we merely note the existence of this possibility.6

SUMMARY

Table A.1 of Appendix 1 lists all the arithmetic operations and their execution
as matrix operations, each with an example.
Table A.2 again lists the arithmetic operations and their execution as field
operations.
N
TH E C
The MATLAB demonstration program aritdemo.m in the accompany-
D
O

ing software illustrates the different possibilities associated with arithmetic


operations. In particular, it provides practical experience with the difference
between matrix and field operations and with the matrix concept in MATLAB.
It can be started7 by copying aritdemo to the command window.

PROBLEMS

Work through the following problems for practice with arithmetic operations.
NOTE Solutions to all problems can be found in Chapter 4.

Problem 8
Start the MATLAB demonstration program aritdemo.m by calling the
command aritdemo in the MATLAB command window and work through
the program.
6
See the MATLAB 7 handbook.
20 INTRODUCTION TO MATLAB & SIMULINK

Problem 9
Calculate

1. the standard scalar product of the vectors


   
x = 1 2 12 −3 −1 and y = 2 0 −3 1
3 2

using a matrix operation and a field operation,


2. the product of the matrices
   
−1 3.5 2 1 0 −1
A= 0 1 −1.3 and B = −1.5 1.5 −3 ,
1.1 2 1.9 1 1 1

3. using a suitable field operation calculate the matrix


 
−1 0 0
C= 0 1 0
0 0 1.9

from the matrix


 
−1 3.5 2
A= 0 1 −1.3 .
1.1 2 1.9

Problem 10
Test left division A\b with the matrix
2 2
A=
1 1
and the vector
2
b =
1
and interpret the result.
Problem 11
 with the matrix
Test right division b/A
2 2
A=
1 1
INTRODUCTION TO MATLAB 21

and the vector


 
b = 2 1
and interpret the result.
Problem 12
Calculate the inverse matrix of
 
1 1 1
M= 1 0 1
−1 0 0

using right (or left) division.

1.2.3 Logical and Relational Operations


We shall not go into logical and relational operations in detail here, but only
consider the most basic elements. In principle this involves operators that
act as field operators (i.e., they operate componentwise on the entries in a
vector or matrix) and yield logical (truth) values as the result.
For example, you can check whether the components of two matrices in
the same terms have an entry = 0 (=logically true). The following MATLAB
sequence shows how this is done using the logical operator & (logical AND)
and what the result of this operation is.
>> A=[1 -3 ;0 0]

A =

1 -3
0 0

>> B=[0 5 ;0 1]

B =

0 5
0 1

>> res=A&B

res =

0 1
0 0
22 INTRODUCTION TO MATLAB & SIMULINK

The resulting matrix res only contains a single 1 (logically true), where the
corresponding components of the two matrices are both  = 0 (logically true),
and is 0 (logically false) everywhere else.
The relational operators or comparison operators work in a similar fash-
ion. The following sequence checks which components of matrix A are greater
than the corresponding components of matrix B. The matrices from the
preceding example are used.
>> comp = A>B

comp =

1 0
0 0

The comparison matrix comp shows that only the first component of A is
greater than that of B.
It hardly needs to be pointed out that here, as with all field operators,
the dimensions of the matrices must be identical.
Other relational operators include ≥ and ≤ (in MATLAB syntax these
are <= and >=) and < , as well as == (equal) and ~= (unequal). Besides the
above mentioned logical AND, we have the logical operators logical OR (|),
logical negation (~), and exclusive OR xor.
Further information on this topic, as well as on the other operations and
functions, is available in MATLAB-help (Section 1.5). For comments relating
to this section, you can, for example, search for the keyword operators
under the menu command Help - MATLAB help. Alternatively, you can
enter help ops in the MATLAB command window. In both cases you
obtain a list of MATLAB operators that includes the logical and relational
operators, among others.
As an illustration of the capabilities of this operator class we give an
example that shows up in many simulations. The problem is to select each
component from a result vector which exceeds a particular value, say 2,
and form a vector out of them. This can be done with the following
sequence:
>> vect=[-2, 3, 0, 4, 5, 19, 22, 17, 1]

vect =

-2 3 0 4 5 19 22 17 1
Exploring the Variety of Random
Documents with Different Content
finalement, de la saleté en abondance et une variété d’odeurs
nauséabondes que le vent du nord ne saurait chasser, voilà des
choses que l’on peut considérer tout à fait indépendamment de
« l’Esprit de Démocratie », ou de « l’Avenir de ce grand pays au
développement puissant ». Dans tout autre pays elles passeraient
pour un signe de négligence, de malpropreté et d’incapacité. Ici, on
vous explique et on vous répète, que c’est une preuve de la rapidité
avec laquelle la ville a grandi et de l’enviable indifférence de ses
citoyens pour les questions de détail. — Un de ces jours, me dit-on,
on s’occupera sérieusement de remédier à cet état de choses. Les
dirigeants de la ville, hommes corrompus, seront balayés par un
cyclone, par un ouragan, ou par quelque explosion grandiose et
retentissante d’indignation populaire ; on élira alors à l’unanimité des
hommes capables qui toucheront, à juste titre, les appointements
énormes actuellement alloués à des étrangers incapables pour des
balayages de rues, et tout ira bien. C’est alors que la licence
inculquée par les gouvernants chez les gouvernés, pendant les
trente, quarante, ou peut-être cinquante années passées ;
l’insouciance brutale du public en ce qui touche les devoirs des
citoyens ; l’endurcissement et l’élasticité de la morale populaire et le
dédain insensé de la vie humaine, engendrés par les lois
impuissantes et encouragés par la familiarité avec des accidents
évitables et une négligence criminelle, disparaîtront
miraculeusement. Si les lois de cause à effet qui gouvernent même
le peuple le plus libre de la terre affirment qu’il en est autrement, tant
pis pour ces lois. L’Amérique fait les siennes. Derrière elle se tient le
fantôme de la guerre la plus sanglante du siècle, suscitée dans ces
pays paisibles à force de s’accoutumer le mépris des lois, de laisser
aller les choses, par l’incapacité et le dédain aveugle pour tout sauf
le besoin matériel du moment présent, tant et si bien que l’heure
depuis longtemps conçue et oubliée se dressa toute armée et que
les hommes s’écrièrent : « Voici une crise imprévue ! » et
s’entretuèrent au nom de Dieu pendant quatre années.
Dans une contrée païenne les trois choses qui passent pour être
les piliers d’un gouvernement passable, sont : le respect de la vie
humaine, la justice criminelle et civile, autant que l’homme est
capable de rendre la justice, et de bonnes routes. Dans cette cité
chrétienne les habitants attachent peu d’importance à la première
(leurs journaux, leurs conversations et leurs actes en font foi) ; ils
achètent et vendent la seconde à un certain prix fixe, ouvertement et
sans honte, et paraissent, semble-t-il, se passer aisément de la
troisième. On s’attendrait presque à ce que le sens de l’humour,
inhérent à la race, les empêche d’espérer rien que des louanges,
épaisses, excessives et serviles de la part de l’étranger en visite
chez eux. Mais non ; si on se tait, ils forgent eux-mêmes des éloges
qu’ils mettent dans votre bouche sur leurs qualités et mérites,
agissant par là, envers leur propre pays qu’ils prétendent honorer,
comme agit le charlatan qui fait la réclame de ses pilules ; s’il vous
arrive d’exprimer votre opinion, — mais vous verrez, par vous-
même, les conséquences de votre franchise. Ils ne se rendent pas
compte qu’avec les mensonges et les invectives, c’est à eux seuls
qu’ils font du tort. Le blâme de toutes les imperfections de leur ville
ne retombe pas entièrement sur les hommes, généralement
d’extraction étrangère, qui gouvernent la cité ; car ils trouvent un
peuple fait pour eux, gens sans lois, prêts à fermer les yeux sur une
infraction aux règlements commise par les voisins, à condition qu’ils
puissent eux-mêmes à leur tour en faire autant avec profit, et qui,
dans leurs rares loisirs, sont bien aises de sourire en entendant
raconter les détails d’un coup de fraude habilement mené. Mais,
vous dit l’Américain cultivé : « Donnez-nous le temps. Donnez-nous
le temps et nous arriverons à quelque chose ! » — Tandis que l’autre
type d’Américain, celui qui est agressif, s’empresse de mettre sous
le nez de l’étranger quelque spécimen de travail bâclé, à moitié fini,
en le présentant comme le résultat d’un effort achevé. Je ne connais
rien de plus agréable que d’écouter pendant un temps strictement
limité un enfant qui vous raconte ses projets pour quand il sera
grand ; mais lorsque ce même enfant, à la voix forte, devenu
exigeant, impudiquement avide de louanges, aussi susceptible que
le plus maladif blanc-bec, vient vous barrer partout la route et vous
ennuyer avec la même histoire, dite sur le même ton, on commence
à soupirer après quelque chose de terminé — mettons l’Égypte et
une momie bien morte. Il n’est ni prudent, ni bienséant, d’insinuer
que le gouvernement de la plus grande ville des États-Unis n’est que
le despotisme de l’étranger, par l’étranger, pour l’étranger, tempéré,
de temps à autre, par des insurrections de gens convenables. Seul,
le Chinois lave le linge sale des autres peuples.

Saint-Paul, Minnesota.

Oui, c’est très bon de partir encore une fois et de reprendre


l’existence éternellement renouvelée du vagabond, flânant dans les
cités nouvelles, bien au courant des mœurs des chiens, des bébés
et des voitures d’enfants de la moitié du globe et suivant la trace des
saisons à la croissance des fleurs dans les jardins d’autrui. St-Paul,
située à la porte des greniers du Dakota et du Minnesota, réunit tous
les suffrages sauf ceux de Minneapolis, sise à dix-sept kilomètres
d’ici, qu’elle déteste et qui prend envers elle des airs de protection.
Elle s’intitule la capitale du Nord-Ouest, et ses habitants portent non
seulement le haut de forme de soie commercial, mais aussi le feutre
large et mou de l’Ouest. Elle parle une autre langue que celle des
New-Yorkais et, (signe évident que nous sommes loin à l’intérieur
des terres) ses journaux discutent avec ceux de San Francisco sur
les démêlés au sujet des tarifs et sur la concurrence des
compagnies de chemins de fer. St-Paul date déjà de plusieurs
années, et si l’on commettait l’imprudence d’aller dans les quartiers
commerçants de la ville on serait bien vite et amplement renseigné
sur son histoire. Mais il faut chercher dans les quartiers bourgeois
toute la supériorité de St-Paul qui, à l’instar d’autres cités, est
entourée de vastes banlieues qui rendent l’étranger jaloux et où l’on
trouve ce que l’on ne rencontre pas au centre de la ville, des rues
bien pavées ou recouvertes d’asphalte, plantées d’arbres, bordées
de contre-allées bien entretenues et parsemées de maisons
possédant un cachet particulier que des barrières rustiques ne
séparent point les unes des autres ; chacune s’élève sur son carré
de gazon soigneusement tondu et descendant jusqu’au trottoir. Le
matin c’est toujours dimanche dans ces rues. Les tramways
électriques ont emmené les hommes à leurs affaires en ville ; les
enfants sont à l’école et les gros chiens, plus de trois pour chaque
bambin absent, sont étendus, le museau dans l’herbe tuée par
l’hiver, se demandant combien il faudra aux jeunes pousses avant
qu’il soit possible à un gentleman de prendre ses herbes
médicinales au printemps. L’après-midi, les enfants sur des tricycles
montent et descendent les rues en zigzaguant, accompagnés,
devant et derrière, de la proportion voulue de gros chiens ; les
tramways, remontant la côte, commencent à déposer chaque
voyageur chez lui, à la porte de la maison que pour lui-même il s’est
construite (bien que l’architecte l’ait poussé à ajouter cette
insignifiante petite tour en mansarde et cette loge inutile), et, tout
naturellement, le crépuscule amène les amoureux qui se promènent
deux par deux le long des chemins si paisibles. On peut presque
dire la date exacte de construction des maisons, qui remonte soit au
temps où l’on dansait la gigue, lorsqu’il incombait aux gens
respectables d’adopter les barreaux façonnés sans beauté et les
pignons ajourés ; ou bien aux jours de l’engouement pour
l’architecture coloniale, c’est-à-dire, maisons peintes en blanc,
garnies de colonnes cannelées ; ou bien encore à l’ère plus récente
de l’architecture domestique, mélange fort agréable de toits peints,
de lucarnes encapuchonnées, de curieuses marquises et de portes
en forme de niches. En présence de tout cela, on commence à
comprendre pourquoi les Américains, visitant l’Angleterre, sont
frappés par ce qui est ancien et non par ce qui est moderne.
L’Américain n’a guère plus de cent ans d’avance sur l’Anglais en ce
qui concerne le plan, le confort, l’installation économique de maisons
et, chose fort importante, l’emploi d’appareils destinés à supprimer la
main d’œuvre. De Newport à San Diego, vous serez amené à faire
les mêmes remarques.
Avant de quitter St-Paul je tiens à lui rendre un dernier hommage
de respect et d’admiration. Une petite maison brune, seule de son
espèce, sise à l’extrémité d’une avenue, semble dormir avec tous
ses volets clos. Cependant le phaéton d’un docteur est arrêté devant
la porte où se trouve accrochée une grande pancarte bleue et
blanche portant ces mots : « Fièvre scarlatine » — Oh ! très
admirable municipalité de St-Paul ! Ce sont ces petits détails et non
point les cris et le tapage sur les places publiques qui font la
grandeur, l’indépendance et le respect d’une nation. Ce soir, dans
les tramways, on parlera de blé, tout en envoyant des pointes à
l’adresse de Minneapolis et Duluth qui réclame vingt pieds d’eau la
réunissant à l’Atlantique — tout cela sans grande importance, à côté
de ces rues et de cette pancarte.

Le lendemain.

— Il y a cinq jours on ne voyait pas un pouce de terre, car la


neige recouvrait tout, dit le contrôleur debout dans le wagon de
queue du Great Northern. Il parle comme si la neige avait caché un
trésor inestimable, et cependant voici tout le spectacle qui nous est
offert : voie ferrée unique, rangée de poteaux télégraphiques
chancelants, se terminant en un point, et un estompage à l’horizon ;
à gauche et à droite, large houle, comme en pleine mer, seule et
immense plaine couverte de champs de blé, qui attend le printemps,
parsemée de loin en loin de fermes construites en bois, de
moissonneuses et de lieuses brevetées presque aussi grosses que
les maisons, de meules qui restent en surplus de l’abondante récolte
de l’an dernier, et marbrée çà et là de veines noires indiquant que
les précoces travaux de labour ont déjà commencé. La neige s’étend
en quelques dernières traînées que le vent fait tourbillonner le long
de la voie ; d’une extrémité à l’autre de l’horizon, tout n’est que
marne argileuse et sombre, couverte d’herbe endormie par le froid,
que le soleil d’une seule année, semble-t-il, ne pourra jamais
réveiller. C’est là le grenier du pays, pays où le fermier qui supporte
les charges de l’État, et qui, par conséquent, impute à l’influence
directe de la loi Mac Kinley la récolte extraordinaire de l’an passé, a
aussi à endurer la monotonie lugubre de la terre et du ciel. Il ne perd
pas la tête car il est très occupé, mais sa femme devient folle
parfois, comme ses compatriotes dans l’État de Vermont. La nature
n’a pas mis une grande variété dans cette immense terre productrice
de blé. On dit que le vent faisant courir des ombres dans les blés en
épis, sur des kilomètres et des kilomètres d’étendue, engendre
comme le vertige chez ceux qui sont forcés de regarder sans
pouvoir détourner les yeux. Et l’on raconte une histoire, véritable
cauchemar, d’un couple qui avait vécu quatorze ans dans un poste
militaire, dans une région semblable à celle-ci, avant d’être transféré
à West Point, au milieu des collines, de l’autre côté de l’Hudson. La
femme vint à New-York, mais hantée de plus en plus par la terreur
que lui inspiraient les maisons géantes, elle fut soudain atteinte de
méningite et, dans son délire, sa grande frayeur était que les
monstres, en s’écroulant, ne vinssent s’écraser sur elle. C’est une
histoire véridique.
Ici, on prépare la moisson avec des charrues à vapeur.
Comment, en effet, pourrait-on suffire aux sillons infinis à l’aide de
chevaux seulement ? On attaque la terre avec des machines munies
de dents, de crans et de longues pointes, qui exposées dans des
magasins paraîtraient monstrueuses, mais qui ne sont ici que des
taches sur l’herbe jaune. Même la locomotive est intimidée en leur
présence. Un train de marchandises suit une ligne qui sort de
l’horizon bleu pour rencontrer à nouveau l’azur du ciel. Ailleurs le
train démarrerait avec un rugissement joyeux et vibrant, mais ici il
glisse furtivement le long des poteaux télégraphiques, dans un
murmure plein de crainte, glisse et s’enfonce dans le sol.
Puis voici une ville disparaissant dans la boue noire, une ville aux
maisons éparses, construites en planches épaisses d’un pouce, qui
possède des entrepôts de grains d’un rouge terne. Mais la
campagne refusant d’être domptée, même sur quelques centaines
de mètres, toutes les rues de la ville débouchent dans l’infini ; c’est
comme si, à son tour, celui-ci tout entier, arrivant du dehors sans
asile, se précipitait à fond de train à travers elles. Vers le soir, sous
un ciel gris, passe rapide devant mes yeux un tableau sans cadre de
morne désolation. Au premier plan, un chariot de ferme embourbé
presque jusqu’aux essieux, la boue dégouttant des roues aux
mouvements lents, tandis que le charretier fouette ses chevaux.
Derrière lui, sur un tertre d’herbe détrempée et marécageuse,
séparé du reste du paysage par des barrières nues, se trouve un
cimetière où reposent aujourd’hui dans une indifférence absolue,
sous des pierres tombales ornées de croix en bois couvertes
d’entailles et usées par les intempéries, des citoyens qui, dans leur
temps, ont eux aussi fouetté des chevaux et semé du blé. — Et je
songe que, pour l’âme récemment libérée du corps, semblable
sépulture doit être plus affreuse encore que les profondeurs de
l’Océan.
A mesure que nous avançons vers le nord, la neige augmente et
la Nature travaille ferme à briser le sol pour le printemps. Le dégel a
inondé toutes les dépressions de terrain dans un déluge maussade
d’un gris noir, et les surfaces plates en perspectives illimitées
disparaissent sous six pouces d’eau. Les petits aqueducs sont pleins
jusqu’au bord, tandis que les bancs de glace flottante viennent se
heurter contre les piles en bois des ponts, faisant entendre un tic-tac
sonore. Mais soudain résonne quelque part dans cette étendue, près
des wagons, un joyeux cliquetis d’éperons, et un homme de la police
montée canadienne passe en se pavanant, coiffé d’un bonnet à poil
noir, orné d’un pompon jaune retombant sur le côté, tiré à quatre
épingles et se redressant de toute sa hauteur. On a envie de lui
serrer la main, parce qu’il a l’air propre, qu’il ne rentre pas les
épaules, ni ne crache, que ses cheveux sont bien brossés et qu’il
marche comme un homme. Puis un employé de la douane surgit et
se montre bien trop curieux au sujet de cigares, de whisky, et de
l’eau de toilette de la Floride. Heureusement que Sa Majesté la
Reine d’Angleterre et Impératrice des Indes nous a sous sa garde.
Rien n’a changé dans le paysage et Winnipeg, qui est pour ainsi dire
un centre de distribution pour émigrants, baigne jusqu’aux genoux
dans l’eau du dégel. L’année a changé pour tout de bon et voici déjà
quelqu’un qui parle de la première « poussée de glace » à Montréal,
1.300 ou 1.400 milles à l’Est.
Les trains ne marchent pas le dimanche à Montréal, et c’est
aujourd’hui mercredi ; conséquemment le Canadien Pacifique forme,
à Winnipeg même, un train pour la direction de Vancouver. Détail
utile à se rappeler, car peu de personnes empruntent ce train et l’on
évite ainsi la ruée de touristes qui filent à l’ouest prendre le bateau
pour Yokohama. On peut alors disposer du wagon et des services
du contrôleur. Ce jour-là, le nôtre, profitant de cette morte-saison, se
divertit en jouant de la guitare, ajoutant au voyage une note gaie et
presque triomphale bien qu’en désaccord ridicule avec le paysage.
Durant vingt-huit heures interminables la locomotive traîna son ennui
à travers des étendues plates, velues, poudrées, côtelées et
tachetées de petits flocons que le vent balaie comme des grains de
poussière ; nous traversions l’Assiniboia. De temps en temps et sans
aucune raison apparente on croisait une ville ; puis des districts
ruraux ; à un endroit nous aperçûmes des traces de buffle sur le sol
où jadis il se pavanait dans son orgueil, et un peu plus loin un
monticule d’ossements blancs, qu’on croit être ceux du dit buffle, et
ce fut à nouveau le désert et la solitude. Certaines parties de terre
paraissaient fertiles, mais en général on aurait dit que l’oubli régnait
sur cette immensité, engendrant tout alentour un ennui éternel.
Au crépuscule — sorte de crépuscule surnaturel — un autre
spectacle singulier nous attendait : une ville construite en bois,
encaissée au milieu de terres basses ondulées et sans arbres, où
une rivière bruyante coulait invisible entre des rives escarpées ; la
caserne d’un détachement de police montée ; un petit cimetière où
reposaient d’anciens soldats de cavalerie ; un jardin public d’une
symétrie guindée et attristante avec des allées de gravier, et des
sapins d’un pied de haut ; quelques constructions attachées à la
gare ; des femmes blanches allant et venant, tête nue dans l’air
glacial ; des Indiens, drapés dans des couvertures rouges, en train
de vendre des cornes de buffles et marchant d’un pas traînant le
long du quai ; puis, à dix mètres à peine de la voie, un ours d’un brun
rougeâtre et un jeune ourson dans des cages, dressés sur leurs
pattes de derrière et mendiant de la nourriture. C’était un spectacle
plus étrange que ne saurait l’évoquer cette description banale, c’était
comme si l’on ouvrait une porte sur un monde inconnu. Le seul détail
rebattu était le nom de l’endroit : Medicine Hat, qui m’avait frappé
immédiatement comme étant la seule appellation en harmonie avec
ce lieu, — qui devint une ville plus tard. J’y étais venu trois ans
auparavant, lorsqu’elle n’avait pas encore atteint ce développement
et je me rappelle que j’avais voyagé sans billet dans un fourgon.
Le lendemain matin nous nous trouvâmes sur la ligne du
Canadien Pacifique, telle que les livres la décrivent. D’ailleurs la
plume d’aucun écrivain ne pourrait rendre justice au paysage
d’alentour. Les guides s’efforcent, mais sans y parvenir, d’en donner
des descriptions, destinées à être lues en été, parlant de cascades
impétueuses, de rochers couverts de lichen, de pins ondulant sous
la brise et de montagnes à la crête neigeuse ; mais en avril il n’existe
rien de tout cela. Le lieu est figé, mort comme un cadavre glacé ; le
torrent de la montagne est transformé en une émeraude de glace du
vert le plus pâle se détachant sur la blancheur éclatante de la neige ;
les tronçons de pins sont coiffés d’un capuchon blanc en forme de
champignon énorme ; les rochers disparaissent sous cinq pieds de
neige ; et avec les roches, les arbres abattus, les lichens, tandis que
blanches et muettes les lèvres qui bordent la voie pratiquée dans le
flanc de la montagne découvrent dans une grimace leurs crocs de
glaçons géants. A l’arrêt du train on cherche vainement à percevoir
parmi les collines le moindre signe de vie ou d’énergie. La neige a
étouffé les rivières tandis que les immenses viaducs s’en vont
escaladant ce qui à l’œil paraît être de la mousse de savon dans
quelque baquet énorme. Les couches de neige anciennes, proches
de la voie, sont noircies et tachées par la fumée des locomotives,
mais les yeux aveuglés par ailleurs aiment à s’y reposer. Cependant
ceux qui habitent le long de la voie ne prêtent aucune attention aux
détails du paysage. A une halte, sise dans une gorge gigantesque,
murée par les neiges, un homme sort en titubant d’un minuscule
cabaret, et s’avance jusqu’au milieu de la voie où une demi-
douzaine de chiens sont en train de chasser un porc égaré sur les
rails. Il est ivre, d’une ivresse parfaite et éloquente ; il chante, agite
les mains et voici qu’il s’effondre derrière une locomotive, tandis que
d’en haut le contemplent les quatre plus beaux pics du monde,
chefs-d’œuvre du Créateur. L’éboulement de terre qui aurait dû
mettre ce cabaret en miettes, manquant son but, est venu
s’effondrer quelques milles plus bas sur la ligne. Le flanc d’un
coteau, en rêvant au printemps, bougea et vint heurter un train de
marchandises qui passait. Voilà pourquoi notre convoi descend avec
précaution, dans un grincement de freins, car la locomotive du train
sinistré nous précédait de peu, et l’on voit la défunte gisant
maintenant, la tête en bas, dans la terre molle, à trente ou à
quarante pieds au-dessous, et disparaissant presque sous deux
longs wagons chargés de bardeaux négligemment plantés sur elle.
Tout cela ressemble tellement à un train-jouet qu’un enfant aurait
jeté de côté, qu’on n’en saisit le sens que lorsqu’une voix s’écrie :
« Personne de tué ? » et qu’une autre répond : « Non, tout le monde
a sauté » — et l’on ressent comme une insulte personnelle cette
incurie de la montagne qui aurait pu endommager votre propre vie
sacrée. Dans ce cas… Mais le train traverse maintenant un pont sur
chevalets, puis un tunnel, puis un autre pont. C’est à cet endroit,
paraît-il, que tout le monde commença à désespérer de pouvoir
construire la ligne, car on ne voyait pas d’issue possible. Mais un
homme vint, comme cela arrive toujours, et on fit une pente par ici,
une courbe par là, un viaduc plus loin, et… la ligne continua son
chemin ! C’est ici d’ailleurs qu’on nous raconta l’histoire du Canadien
Pacifique, racontée comme on redit un conte répété maintes fois,
avec des exagérations et des omissions, mais histoire malgré tout
impressionnante. Au début, lorsqu’on désirait créer la Confédération
du Canada, la Colombie Britannique soulevait des objections et
refusait son adhésion, mais le Premier Ministre de ce temps-là lui
promit un pot-de-vin, un cordon d’acier réunissant les deux côtes et
qui ne devait jamais se rompre. Puis tout le monde se mit à rire,
chose nécessaire, paraît-il, à la santé de la majorité des vastes
entreprises, et tandis qu’on riait, on travaillait toujours. On accorda
au Canadien Pacifique un morceau de ligne par ci, un autre par là, et
presque autant de terrain qu’il fallait, et l’on riait encore lorsque le
dernier rivet fut posé entre l’est et l’ouest, à l’endroit même où
l’ivrogne s’était étalé derrière la locomotive. La ceinture de fer
s’étendait désormais d’une marée à l’autre ainsi que l’avait annoncé
le Premier Ministre tandis que les Anglais s’écriaient : « Que c’est
intéressant ! » puis se mirent à parler de « l’exagération commise
dans l’estimation des contingents militaires ». Incidemment, l’homme
qui nous renseignait (il n’était pas en relations avec le Canadien
Pacifique) nous expliqua les bénéfices réalisés par la ligne en
encourageant l’immigration. Il nous raconta l’arrivée à Winnipeg, un
certain dimanche, d’un train complet de paysans écossais. Ces gens
voulaient à toute force s’arrêter à l’instant même pour fêter le
dimanche, eux et le petit troupeau qu’ils avaient emmené avec eux.
Ce fut l’agent de Winnipeg qui dut aller les trouver et leur expliquer,
(il était Écossais lui aussi, de sorte qu’ils ne comprirent pas très bien
ses raisons) l’inconvenance qu’il y avait à disloquer la circulation de
toute la Compagnie. Leur propre ministre fit donc un service dans la
gare ; ensuite, l’agent leur fit servir un bon repas, les encouragea en
dialecte écossais, sur quoi ils se mirent à verser des larmes, puis
poursuivirent leur route pour s’installer à Moosomin où, comme dans
les contes de fées, ils vécurent heureux jusqu’à la fin de leurs jours.
Ce fut avec respect, presque avec vénération, que notre compagnon
parla du directeur, chef de la ligne de Montréal à Vancouver. Ce
directeur habitait une demeure princière à Montréal, mais de temps
à autre il partait dans son train spécial, parcourait ses 3.000 milles à
une allure de 50 à l’heure. La vitesse réglementaire est de 22, mais
c’est un « casse-cou » et peu de mécaniciens tenaient à l’honneur de
conduire son train. C’était un homme mystérieux qui « portait gravé
dans la tête le plan de la ligne entière » et, qui plus est, connaissait
intimement les possibilités offertes par des régions éloignées qu’il
n’avait jamais vues ni traversées. On trouve toujours sur chaque
grande ligne un homme de cette trempe, et des mécaniciens du
grand Ouest en Angleterre ou des chefs de gare européens —
asiatiques sur le grand Nord-Ouest aux Indes — peuvent vous
raconter des histoires semblables. Ensuite un de nos compagnons
de voyage se mit à parler, comme l’avaient fait beaucoup d’autres,
d’une union possible entre le Canada et les États-Unis ; son langage
n’avait rien de commun avec celui de Mr. Goldwin Smith ; il était
brutal, par endroits, et se résumait en un refus catégorique à traiter,
en quoi que ce soit, avec un pays qui était pourri avant que d’être
mûr, un pays qui comptait sept millions de nègres qui n’étaient pas
encore amalgamés à la population, et où le type de la race était
resté stationnaire, n’ayant encore que des notions primitives sur le
meurtre, le mariage et l’honnêteté. — Nous avons adopté leurs
façons de faire en matière politique, dit-il sur un ton triste, à force de
vivre à côté d’eux, mais je ne crois pas que nous désirions nous
associer à leurs autres gâchis. Ils disent qu’ils n’ont pas besoin de
nous ; ils le répètent même sur tous les tons, mais il y a
certainement là-dessous quelque motif caché, sans quoi ils ne
mentiraient pas à ce point.
— Mais s’en suit-il nécessairement qu’ils ne disent pas la vérité ?
— Bien sûr, j’ai vécu au milieu d’eux. Il n’y a pas plus faux que
ces gens-là. Il doit y avoir quelque satanée tricherie derrière tout
cela.
Sa conviction était inébranlable ; il avait vécu parmi « ces gens-
là, » peut-être avait-il été roulé en affaires. — Qu’ils restent chez
eux, avec leurs mœurs et leurs coutumes, ajouta-t-il.
Cela n’est point gai et vous glace. Cependant on parlait bien
différemment à New-York, où l’on représentait le Canada comme
une prune mûre prête à tomber dans la bouche de l’Oncle Sam au
moment opportun. Le Canadien n’éprouve pas une tendresse
spéciale pour l’Angleterre, car la mère des colonies a un talent
merveilleux pour éloigner d’elle, par négligence, les membres de sa
propre maison ; peut-être aime-t-il son pays ?
Nous sortîmes de la neige en traversant des kilomètres garnis
d’abris contre la neige, étayés de poteaux de trente centimètres
d’épaisseur, recouverts de planches épaisses de deux pouces. A un
certain endroit, une avalanche était venue heurter l’angle d’un de
ces abris et l’avait entamé comme un couteau entame un fromage.
Au haut des collines, des hommes avaient élevé des barrières pour
détourner les bancs de neige, mais la rafale blanche avait tout
balayé et la neige s’étendait en couches épaisses de cinq pieds sur
le toit des abris. Au réveil, nous nous trouvâmes aux bords du
Fraser, rivière boueuse, où le printemps se hâtait de venir à notre
rencontre. La neige avait disparu : les fleurs carminées du groseillier
sauvage étaient écloses ; les aunes bourgeonnants, habillés de vert
brumeux, se détachaient sur le noir bleu des pins ; les ronces sur les
tronçons d’arbres brûlés, ouvraient leurs toutes jeunes feuilles,
tandis que chaque mousse sur chaque pierre était nouvelle de
l’année et toute fraîche éclose des mains du Créateur. Partout le sol
se déployait en champs défrichés à terre molle et noire. Dans l’une
des gares une poule ayant pondu un œuf, faisait part au monde
entier de son chef-d’œuvre, et le monde entier répondait par une
bouffée de véritable printemps, de printemps qui inonda le wagon à
l’atmosphère lourde, nous attira sur le quai pour humer l’air, chanter,
nous réjouir, cueillir des iris des marais mous et verts, les jeter aux
poulains, et pousser des clameurs à l’adresse des canards
sauvages qui s’élevaient d’un petit lac vert comme un joyau. Que
Dieu soit béni, lui qui permet que dans les voyages on puisse suivre
les saisons. Ce printemps, mon printemps, que j’avais perdu en
novembre dernier en Nouvelle-Zélande, je vais maintenant le
conserver précieusement au Japon et durant l’été pour le retrouver
encore en Nouvelle-Zélande.
Et voici maintenant les eaux du Pacifique, et voici Vancouver,
cette ville, complètement dépourvue de défenses convenables, qui
s’est développée de façon extraordinaire durant ces trois dernières
années. A l’embarcadère du chemin de fer, où pas un seul canon ne
veille sur elle, repose « l’Impératrice des Indes », qui fait le service
entre l’Amérique et le Japon, et quel nom de meilleur augure
pourrait-on désirer rencontrer au dernier chaînon d’une des
puissantes chaînes de l’Empire ?
LA LISIÈRE DE L’ORIENT

Le brouillard se dégageait peu à peu de la rade de Yokohama ;


une centaine de jonques avaient hissé leurs voiles en vue de la brise
matinale, et l’horizon voilé était pointillé de carrés d’argent estompé.
Sur le fond de brume ouatée se détachait, blanc et bleu, un navire
de guerre anglais, tant l’aube était jeune, et la surface des eaux
s’étendait douce et lisse comme l’intérieur d’une coquille d’huître.
Deux enfants vêtus de bleu et de blanc, aux membres tannés, rosis
par l’air vif, maniaient, à la godille, une merveilleuse barque de bois
couleur citron qui, à travers l’immobilité complète et les étendues
plates teintées de nacre, fut notre embarcation féerique jusqu’à la
côte.
Il y a maintes et maintes façons d’entrer au Japon, mais la
meilleure est d’y descendre de l’Amérique par l’Océan Pacifique, du
pays des Barbares par la mer profonde. Lorsqu’on vient de l’Orient,
la lumière crue des Indes et la végétation tropicale, insolente, de
Singapour émoussent la vue, et la rendent insensible aux demi-tons
et aux petites nuances. C’est à Bombay que l’Odeur de toute l’Asie
envahit le navire à des milles de la côte, et s’empare des narines du
voyageur jusqu’à ce qu’il ait quitté l’Asie à nouveau. C’est une odeur
violente et provocante, susceptible de faire naître des préventions
dans l’esprit de l’étranger, mais qui est néanmoins de la même
famille que la douce et insinuante senteur qui flottait dans les légers
souffles de l’aurore lorsque la barque féerique toucha la côte —
parfum de bois frais et très propre, de bambou fendu, de fumée de
bois, de terre humide, et de choses que mangent ceux qui ne sont
pas des blancs ; odeur toute familiale et réconfortante. Puis ce fut à
terre le son d’une langue orientale qui semble plus ou moins belle
selon qu’on la comprend. Les races occidentales s’expriment dans
des langues très diverses, mais des voix d’Européens entendues à
travers des portes fermées ont le diapason et la cadence de
l’Occident. Il en est de même en Orient. Une rangée de coolies
traîneurs de pousses-pousses étaient accroupis au soleil, bavardant
entre eux et ils semblaient souhaiter la bienvenue dans une langue
qui pour ceux qui l’écoutaient devait être aussi familière que
l’anglais. Ils causaient, causaient sans arrêt, mais le spectre des
mots connus ne s’éclaircissait pas jusqu’à ce que soudain l’Odeur
redescendît par les larges rues, disant qu’ici c’était l’Orient, l’Orient
où rien n’importe et où des bagatelles vieilles comme la Tour de
Babel importent moins que rien, et que de vieilles connaissances
vous attendaient à chaque pas au delà de l’enceinte de la ville.
Puissante est l’Odeur de l’Orient ! Ni chemins de fer, ni télégraphe, ni
docks, ni chaloupes canonnières ne sauraient la bannir, elle durera
autant que les voies ferrées. Celui qui n’a pas senti l’Odeur n’a
jamais vécu.
Il y a trois ans les boutiques de Yokohama étaient suffisamment
européanisées pour satisfaire les goûts les plus mauvais et les plus
pervers ; aujourd’hui c’est encore pis si l’on ne sort pas de la ville
proprement dite. Mais à dix pas au dehors, dans la campagne, toute
la civilisation s’arrête, comme elle cesse dans un autre pays situé à
quelques milliers de kilomètres plus à l’Ouest. Ceux qui parcourent
le globe, les millionnaires avides de dépenser, versant leur argent à
grands flots sur tout ce qui séduit leur fantaisie libertine, nous
avaient expliqué, à bord du paquebot, que suivant le conseil des
livrets-guides, ils s’étaient précipités au Japon craignant que le pays
ne se fût soudain civilisé entre deux services de bateaux. Et
touchant terre ils s’empressèrent de rendre visite aux marchands de
bric-à-brac pour leur acheter des articles qu’on prépare exprès pour
eux, des objets de couleur mauve, lie de vin ou bleu de vitriol. En ce
moment ils doivent avoir un guide « Murray » sous un bras et sous
l’autre un morceau de soie vert pomme où sont brodés un aigle bleu
électrique, au bec couperosé et un « e pluribus unum » en lettres
jaunes.
Nous, qui sommes des sages, restons assis dans un jardin qui
n’est pas le nôtre mais qui appartient au Monsieur là-bas vêtu de
soie couleur d’ardoise. Ce Monsieur, uniquement par égard pour le
décor, condescend à faire le jardinier et, dans cet emploi, est occupé
à balayer délicatement dessous une azalée mourant d’envie
d’éclater, un tas de fleurs rouges tombées d’un cerisier en floraison.
Des marches de pierre abruptes, patinées comme la Nature les
patine à travers de longs hivers, conduisent à ce jardin en longeant
des touffes d’herbe de bambou. Vous voyez que l’Odeur avait raison
en disant que vous retrouveriez de vieux amis. Une demi-douzaine
de pins inclinés et pour ainsi dire la main sur la hanche, d’un noir
bleuâtre, se détachent sur un ciel véritable : pas de ces taches de
brume, pas un de ces bancs de nuages, ni de ces torchons gris
enveloppant le soleil, mais un ciel pur et azuré. Un cerisier, sur une
pente au-dessous d’eux, lance en l’air une vague de fleurs qui vient
se briser à leur pied dans une écume d’un blanc crémeux, tandis
qu’un bouquet de saules laisse tomber en rideau ses pousses
d’émeraude très pâle. Le soleil envoie en ambassadeur à travers les
buissons d’azalée un papillon majestueux à la queue d’hirondelle,
accompagné de son écuyer qui rappelle les petits insectes bleus et
voltigeants des dunes anglaises. La chaleur de l’Orient qui pénètre
et n’effleure pas seulement le corps paresseux, s’ajoute à la lumière
de l’Orient, cette clarté splendide et généreuse qui rend la vue plus
nette sans jamais la troubler. Puis les premières feuilles printanières
clignotent comme de grosses émeraudes et les branches de cerisier
chargées de fleurs rouges deviennent transparentes et s’embrasent
comme une main placée devant une flamme. De petits soupirs
tièdes montent de la terre humide et chaude et les pétales tombés
bougent sur le sol, se retournent, puis se rendorment à nouveau. Au
delà du feuillage, là où le soleil repose sur les toits couleur d’ardoise,
les rizières en terrasses qu’on aperçoit au-dessus des toitures et les
collines qui dominent au loin, c’est tout le Japon, seulement tout le
Japon ; tandis que cet endroit qu’on appelle l’ancienne Légation de
France, c’est le paradis terrestre qui tout naturellement est venu
tomber ici après la Chute.
Comme premier aperçu des beautés qui se révéleront plus tard, il
y a ce toit là-bas, ce toit en étage du temple tout couvert de tuiles
sombres et cannelées, et comme par hasard jeté au delà de
l’extrémité de la falaise où s’étend le jardin. Toute autre courbe des
larmiers ne se serait pas harmonisée avec la courbe des pins ; il
fallait donc la créer telle qu’elle nous frappe maintenant par sa
perfection. Nos gens qui parcourent le globe sont en ce moment à
l’hôtel en train de se battre pour avoir des guides, afin qu’on leur
montre les beautés du Japon qui ne forment qu’un seul spectacle. Il
faut qu’ils aillent à Tokio, puis à Nikko ; qu’ils voient, sans manquer,
tout ce qu’il y a à voir, pour écrire ensuite à leurs familles barbares
qu’ils finissent par s’accoutumer à rencontrer des jambes nues et
brunes. Mais, Dieu soit loué, avant ce soir, ils se plaindront tous d’un
violent mal de tête et de brûlures aux yeux. Il est donc préférable de
se reposer tranquillement et d’entendre l’herbe pousser ; de
s’abreuver de chaleur, des senteurs, des bruits et des vues qui
viennent spontanément s’offrir à vous.
Notre jardin surplombe la rade et en écartant une seule branche
on aperçoit un bateau de pêche à la poupe épaisse et la petite
cabine dont les nattes couleur d’or paille ont été écartées et
découvrent l’intérieur propre et bien tenu de la maisonnée. Le père
qui est pêcheur est accroupi à l’orientale, en train de tisonner un
minuscule foyer rempli de charbon de bois, tandis que la cendre
blanche et légère vole dans le visage d’une grosse poupée
japonaise qu’on aurait pour trois francs cinquante à Londres. Mais la
poupée se réveille soudain, se transforme en un bébé japonais, en
quelque chose qu’on ne saurait acheter à prix d’or, un poupon au
crâne nu, aux jambes vagues et qui s’approche en rampant de la
boîte brune et vernissée, se fait ramasser juste au moment où il allait
avaler des charbons ardents, et déposer derrière un banc de nage,
où il joue du tambour sur un seau, s’adressant de loin à la boîte à
flammes. Une demi-douzaine de fleurs de cerisier glissent d’une
branche, tournoient tremblottantes et tombent à l’eau près de la
poupée japonaise qui, un instant de plus, aurait été par-dessus bord
à la poursuite de ces miracles. Mais cette fois le père la happe par
sa jambe rose, la fourre dans quelque coin où elle disparaît au milieu
des filets bruns ombrés et des cordages couleur sépia, d’où son
toupet seul émerge. Étant orientale, elle ne récrimine pas, et le
bateau s’enfuit rapide pour aller rejoindre la petite flotte au large.
Puis deux marins d’un cuirassé passent le long de la mer, se
penchent au-dessus du canal au pied du jardin, crachent et repartent
en se dandinant. Le marin, au port, est le seul homme qui soit
vraiment supérieur. Pour lui, tout ce qui est rare et curieux se traduit
par : « ces trucs », ou « ces machins-là ». Il ne se presse pas, ne
cherche pas d’épithètes différentes de celles que l’usage met sur
ses lèvres et qu’il sert à toutes les occasions ; mais la beauté de la
vie pénètre insensiblement son être jusqu’au moment où, la boisson
ayant eu raison de lui, il s’attrape avec le sergent de ville de l’endroit,
l’expédie d’un coup de poing dans le canal le plus proche, et règle la
question de la revision du traité par un hoquet. N’empêche que Jack,
à l’entendre, a un grief contre le sergent de ville qui touche un dollar
par chaque marin vagabond qu’il amène devant les Tribunaux
Consulaires, coupable d’avoir allongé sa permission, ou que sais-je
encore. Jack prétend aussi que les petits sergents japonais font
exprès de l’empêcher de retourner à son navire pour le produire
ensuite en justice, tout cela grâce à des tours de lutteur exécutés
avec toute la diablerie de l’art : « il y en a environ une centaine de
ces satanés tours et n’importe lequel suffit pour vous ficher par
terre ». Sachez que lorsque Jack se trouve adouci par la boisson il
ne dit pas de mensonges ; c’est là son grief, dit-il, et l’on devrait les
mettre au courant, ces N… de D… de consuls : « Ils (il s’agit des
sergents de ville) s’entendent tous pour vous emmener à l’Hatoba. »
Le visiteur, qui n’est ni marin ni ivre, ne saurait se porter garant de
cette déclaration et même de rien autre, car il se meut non
seulement au milieu de scènes enchanteresses et d’un peuple
charmant mais encore, ainsi qu’il s’en aperçoit certainement le
premier jour de son arrivée, au milieu de discussions orageuses. Il y
a trois ans, il fallait régler toutes les questions sur-le-champ dans
une véritable orgie de lampions. La Constitution était nouvelle alors ;
la couverture en est gris pâle avec un chrysanthème au dos, et un
Japonais me dit : Maintenant nous avons une Constitution comme
d’autres pays ; ainsi tout va bien. Maintenant nous sommes tout à
fait civilisés à cause de notre Constitution.
(Une histoire qui n’a aucun rapport avec ce qui précède me
revient à la mémoire en ce moment. Savez-vous qu’autrefois les
habitants de l’île de Madère se mirent en révolution juste assez
longtemps pour permettre au poète national de composer un hymne
patriotique, puis que la révolte fut réprimée. Tout ce qu’il en reste
maintenant c’est le chant que vous entendez jouer sur les
« nachettes » (tout petits banjos) au son nasillard, par les soirs de
clair de lune sous les feuillages touffus des bananiers derrière
Funchal. Et le refrain qu’on chante du nez, sur un diapason aigu, est
le mot : « Consti-tuci-oun » !)
Depuis cet heureux événement, il semble que les discussions
surgissent à tout propos, dont la plus importante est celle de la
Revision du Traité. « Observez, dit le Gouvernement japonais, nos
lois, nos lois nouvelles que nous avons soigneusement composées
avec toute la sagesse de l’Occident, et vous pourrez parcourir le
pays à votre guise et faire du commerce où vous voudrez, au lieu de
vivre claquemurés dans des concessions et d’être soumis à la
justice des consuls. Traitez-nous comme vous traiteriez la France ou
l’Allemagne, et nous vous traiterons comme nos propres sujets. »
Ici, vous le savez, la question reste entre les 2.000 étrangers et
les 40 millions de Japonais ; aubaine merveilleuse pour les éditeurs
de Tokio et de Yokohama mais désespoir des voyageurs
fraîchement débarqués, dont le nez, souvenez-vous-en ! est hanté
par l’Odeur de l’Orient, Une, Indivisible, Immémoriale, Éternelle, et
par-dessus tout Instructive.
En vérité, il faut s’éloigner d’un demi-kilomètre au moins, pour
échapper aux indices provocants de la civilisation et arriver aux
rizières plantées derrière la ville. Là, des hommes, coiffés d’un
turban bleu et blanc, travaillent dans la boue noire et épaisse,
jusqu’aux genoux. Le champ le plus vaste atteint, parfois, presque la
largeur de deux nappes de table, tandis que le plus petit est,
mettons, un atome de terrain sous une minuscule falaise trop peu
large pour qu’on y appuie aisément un pousse-pousse, coin de terre
arraché à la rive et où croît une touffe d’orge à portée de l’embrun
des vagues. Les sentiers des rizières sont les bords piétinés des
sillons d’irrigation et les grandes routes sont aussi larges que deux
voitures d’enfant placées l’une à côté de l’autre. Depuis les plateaux
— les beaux plateaux plantés de pins et d’érables, juste aux bons
endroits — le sol descend de terrasses en terrasses de terre riche
jusqu’aux plaines où l’on dirait que chaque ferme au toit de chaume
épais a été spécialement choisie pour s’harmoniser avec le paysage
environnant. En suivant attentivement les gens qui vont à leur travail,
on s’aperçoit qu’un domaine s’étend sur des lots de terrain, séparés
parfois les uns des autres par environ 400 mètres. Le cadastre d’un
village montre que cet éparpillement est apparemment voulu ; on
n’en donne pas les raisons. Ce ne doit pas toujours être aisé
d’établir le cadastre de ces lots de terre, genre de travail qui serait
susceptible de donner une occupation à un grand nombre de petits
fonctionnaires variés du Gouvernement, dont chacun, en supposant
qu’il ait une tournure d’esprit orientale, pourrait rendre la vie du
cultivateur intéressante. Je me rappelle maintenant (un lieu qu’on
revoit pour la deuxième fois évoque des faits qu’on croyait oubliés à
jamais) avoir vu, il y a trois ans, la pile de documents officiels requis
pour une seule ferme. Ils étaient nombreux, systématiques, mais ce
qui les rendait intéressants c’était la somme de travail qu’ils avaient
dû fournir à ceux qui n’étaient ni cultivateurs, ni officiers du Trésor.
Si on connaissait la langue japonaise, on pourrait bavarder avec
ce Monsieur au chapeau de paille et à la ceinture bleue nouée
autour des reins, en train de sarcler à quelques millimètres de ses
orteils nus avec l’arrière-grand-père de tous les sarcloirs qui furent
jamais. Son exposé des impôts locaux manquerait peut-être
d’exactitude mais certainement pas de pittoresque. A défaut de son
témoignage, qu’on veuille bien accepter deux ou trois faits qui
peuvent, ou ne peuvent pas, c’est selon, être d’application générale,
et qui diffèrent dans une certaine mesure des déclarations qu’on
trouve dans les livres. L’impôt foncier actuel est nominalement de
2,5 pour cent, payable en espèces en un règlement annuel effectué
en trois ou, selon d’autres, en cinq fois. Mais, au dire de certains
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like