next up previous contents
Next: Exercise 5 (Vectors) Up: Working with Jasymca Previous: Exercise 4 (Variables)

Vectors und Matrices (1)

These datatypes are either used for multidimensional objects, or for simultaneous calculations on large numbers of data, e.g. for statistical problems. In this chapter we discuss this latter aspect. Linear algebra and the usual vector calculations are treated in chapter 2.9.

Vectors are marked with square brackets. The elements are entered as comma-separated list. The commas may be left if the elements can be distiguished in a unique manner, which however fails in the second example below:

>> x=[1,-2,3,-4]
x = [ 1  -2  3  -4 ]
>> x=[1 - 2  3 -4]       % Caution: 1-2=-1
x = [ -1  3  -4 ]
Colon and the function linspace are used to define ranges of numbers as vectors.
>> y=1:10               % 1 to 10, step 1
y = [ 1  2  3  4  5  6  7  8  9  10 ]
>> y=1:0.1:1.5          % 1 to 1.5, step 0.1
y = [ 1  1.1  1.2  1.3  1.4  1.5 ]
>> y=linspace(0,2,5)    % 5 from 0 to 2.5, equidistant.
y = [ 0  0.5  1  1.5  2 ]

The number of elements in a vector x is calculated with the function length(x), individual elements are extracted by providing the index k like x(k). This index k must be a number in the range 1 to (including) length(x). The colon operator plays a special role: Used as index, all elements of the vector are returned. Additionally, ranges of numbers can be used as index.

>> y(2)                % single element
ans = 0.5
>> y(:)                % magic colon
ans = [ 0  0.5  1  1.5  2 ]
>> y(2:3)              %  index between 2 and 3
ans = [ 0.5  1 ]
>> y(2:length(y))      %  all from index 2
ans = [ 0.5  1  1.5  2 ]
>> y([1,3,4])          %  indices 1,3 and 4
ans = [ 0  1  1.5 ]
>> y([1,3,4]) = 9      %  insert
ans = [ 9  0.5  9  9  2 ]
>> y([1,3,4]) = [1,2,3] % insert
ans = [ 1  0.5  2  3  2 ]

Matrices are handled in a similar way, only with two indices for rownumber (first index) and columnnumber (second index). Rows are separated by either a semicolon or a linefeed during input.

>> M=[1:3 ; 4:6 ; 7:9]
M = 
  1  2  3  
  4  5  6  
  7  8  9  
>> M([1 3],:) 
ans = 
  1  2  3  
  7  8  9  
>> C=M<4
C = 
  1  1  1  
  0  0  0  
  0  0  0

The operators of chapter 2.2 may be applied to vectors and matrices. If scalar, per-element operation is desired, some operators (* / ^) must be preceded by a point to distinguish them from the quite different linear-algebra versions of these operations (see chapter 2.9). Further useful functions are sum(vector) and prod(vector) which return the sum and product of the vectors elements.



Subsections
next up previous contents
Next: Exercise 5 (Vectors) Up: Working with Jasymca Previous: Exercise 4 (Variables)
Helmut Dersch
2009-03-15