User Tools

Site Tools


octave:octave

Octave syntax and library overview

Installing packages

Fetch the package files from octaveforge. Then create (or add to) the file ~/.octaverc the following content:

addpath(genpath('~/octave'))

And run pkg install packagename-1.0.0.tar.gz or whatever the package is called from inside octave. Now the package should be available.

plotting

h = [1,2,3,4,5];
plot(h);
xlabel("some numbers");
print("myfile.pdf", "-dpdf");

This code plots a a vector with a label on the x-axis, and exports it to a pdf file.

h=wavread('h.wav');
hfft=abs(fft(h));
semilogx(hfft(1:end/2))

This code loads an audiofile, and plots its frequency spectrum on a logartihmical scale.

function

function retval = myfunction(param1, param2)
  retval = param1 + param2;
end;

strings

mystring = 'hello world'; % create string
sizeof(mystring) % get length of string
 
mystrilyng2 = [ mystring, 'fisk']; % concatenate two strings

sizeof on works in octave. in matlab the length of a string cannot be obtained!

string array

myemptyarray = {}; % create empty string array.
 
myarray = { 'hello', 'world' }; % create array with two strings.
myarray(1) % prints 'hello'
myarray(3) = 'blah'; %inserts another string into the array.
 
sizeof(myarray) % get number of elements
sizeof(myarray(1)) %get length of first string
 
% Iterate strings in string array
for str = myarray
  disp(str)
end

Note: Arrays are 1-based, not 0-based as they usually are in real programming languages. Note: sizeof is an octave-only function. size can be used to get the array size in matlab.

if then else

a = 1;
 
if a == 1
  "a is one"
end;
 
if a == 2
  "a is two"
else
  "a is not two"
end;

for while

list = 1:10
 
for i = list
  i
end;
 
a = 1;
while a < 11
  a
  a = a + 1;
end; 

switch case

yesno = "yes"
 
switch yesno
case {"Yes" "yes" "YES" "y" "Y"}
  value = 1;
case {"No" "no" "NO" "n" "N"}
  value = 0;
case "blah"
  value = 42;
otherwise
  error ("invalid value");
endswitch

Note: In matlab the endswitch should be replaced by end

More complex examples

rootfolder = pwd % Print Working Directory - specifies root folder so we don't have to cd
for s=scans
  scanfolder=sprintf('ret_scan%02d', s)
  folders=dir([rootfolder,'/',scanfolder,'/*_bg'])
  numfolders=size(folders);
  folderiterator = 1:numfolders(1);
  for folder=folderiterator
    files=dir([rootfolder,'/',scanfolder,'/',folders(folder).name,'/*.mat'])
    numfiles=size(files);
    fileiterator = 1:numfiles(1);
    for file=fileiterator
      file
      filename=[rootfolder,'/',scanfolder,'/',folders(folder).name,'/',files(file).name]
      %filename
      load (filename) % Loads the bg-file (no laser)
    end;
  end;
end; 
octave/octave.txt · Last modified: 2009/04/23 13:54 by deva