echo on
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  A simple octave script with exampes of vector and matrix operations
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%creating a amtrix
%directy writing the entries
A=[1,2;4,5;6 7]

%we can access an element
A(1,2)

%differently
B=[1 2 
4 5 
6 7]
%using formulas for some entries
x=[1+2, sqrt(2), 15/7]

%functions on vectors
sin(x)
%use help to an octave function
help sin
%finding a string in help
lookfor sin


%changing an element
A(1,1)=-3

%extending the range of a vector/matrix
x(6)=4.56

A(1,7)=10

%objects in memory
who
%detailed
whos
%see object B
B
%usunac
clear B
%usunac wszystko 
clear 
who

%colon operator a:h:b
%(generates a vector from a t ob with step h, i.e. x(i)=a +(i-1)*h 
%for  i=1,2,... such that a+i*h <=b)
%here the default step h=1
x=1:5
y=0:0.1:1
A=[1:4 ; 0 5:7; -3:0]
%we can make an error (commneted out - if there is an error then octave stops
%B=[1:3 ; 1:2]

%submatrices
A1=A(1:2 ,  2:3)
%we get the submatrix containing 2 first rows
A2=A(1:2,:) 
%we add a column to A2
[A2 , [1;2]]
%we add a row to it
[A2 ; 1:4 ]
%or
[A2 ; A2]
[A2,A2]
[A2 ,A2;A2,A2]
%we can multiply matrices
x=1:4
%x must be a column (not a row)
x=x'
f=A*x
%we can multiply matrices
B= [ 1 2 ; 3 4]
C= [ 5 6 ; 1 1 ]
B*C
%or element by element
B.*C
%or by a scalar
2*A
%transposing
B=A'
%we remins f=A*x; so we know the solution..
sol=A\f;
%we can check the error
blad=sol -x
%we can get the euclidan norm (2nd)
norm(blad,2) 
%or 1st or supremum
norm(blad,1)
norm(blad,'inf') 
%semicolon at the end makes the command not to prodice any output
%residual error
blres=A*sol -f;
norm(blres,2)

%we can compute  
cond(A)
%identity matrix
I=eye(10)
%or famous ill-conditioned mhilbert Matrix
H=hilb(10); 
cond(H)
cond(I)

% its inverse
Hinv=inv(H);
%is the result right?
norm(H*Hinv-I,2)
%not too good - for not too large size
%check other solvers 
sol=1:10; 
sol=sol'; 
f=H*sol;
x=H\f;
y=Hinv*f;
%error for octave solver
norm(x-sol,2)
%if we multiply by the inverse (but the inverse was computed by the same octave's solver LU...)
norm(y-sol,2)
%what is residual norm
norm(H*x-f,2)
clear
%what's more?

%you can move long statements
y=[1,2,3, ...
5 6 7]


%we can wrtite objects to files
%what we have
who
% t otext file (ascii format)
save -ascii dane.dat
%%we can see the file in an editor or from command line: more dane.dat
%we remove all objects
clear 
%what we have
who
%we read the file to octave session
load dane.dat
who
%there are other text of binary formats e.g.
save -binary dane.bin
clear
who
load dane.bin
who
%and that's it about octave basics