Difference between revisions of "MATLAB1"

From SourceWiki
Jump to navigation Jump to search
Line 13: Line 13:
 
* Replace your loops with vectorised operations, e.g.
 
* Replace your loops with vectorised operations, e.g.
  
replace:
+
For example, if you would like to perform a scalar operation to a vector, '''vec''', (say, multiply each element by 3) then you do not need to write a loop.
 +
 
 +
Replace:
 
<pre>
 
<pre>
 
for i = 1:length(vec)
 
for i = 1:length(vec)
Line 24: Line 26:
 
vec = vec*3
 
vec = vec*3
 
</pre>
 
</pre>
 +
 +
Similarly, if you have two vectors or matrices of the same size, you can perform element-by-element operations using, e.g.
 +
 +
<pre>
 +
m3 = m1 - m2
 +
</pre>
 +
 +
Note that array versions of the multiplication, division and exponentiation operators are '''.*''', '''./''' and '''.^''', respectively.
 +
 +
If you wish to apply the same function to all the elements of an array or vector, then you can pass it as an argument to the function.  If you write your own functions, ensure that the operators that you use inside the function can handle vectors or matrices.
 +
  
 
<!--
 
<!--

Revision as of 10:58, 2 September 2013

An Introduction MATLAB

Introduction

Rather than re-invent the wheel, we'll use some tried and tested tutorial material. The following notes from the Maths department at the University of Dundee are concise, comprehensive, but also easy to read: http://www.maths.dundee.ac.uk/ftp/na-reports/MatlabNotes.pdf


Hints and Tips on Performance

  • Replace your loops with vectorised operations, e.g.

For example, if you would like to perform a scalar operation to a vector, vec, (say, multiply each element by 3) then you do not need to write a loop.

Replace:

for i = 1:length(vec)
  vec(i) = vec(i) * 3;
end

with:

vec = vec*3

Similarly, if you have two vectors or matrices of the same size, you can perform element-by-element operations using, e.g.

m3 = m1 - m2

Note that array versions of the multiplication, division and exponentiation operators are .*, ./ and .^, respectively.

If you wish to apply the same function to all the elements of an array or vector, then you can pass it as an argument to the function. If you write your own functions, ensure that the operators that you use inside the function can handle vectors or matrices.