Difference between revisions of "Tips and tricks"

From Octave
Jump to: navigation, search
(How to declare functions inside a test block: moved to tests)
(Tiny helper functions: new section)
Line 1: Line 1:
 +
=Tiny helper functions=
 +
This is a list of tiny helper functions (the equivalent of e.g., shell aliases), the kind one wuld have on its ''.octaverc'' file.
 +
 +
== replace help with man ==
 +
If you use octave too much, you'll find yourself trying to use ''help'' instead of ''man'' on bash. This will allow you to use ''man'' in your octave instance (you can also create a ''help'' alias for bash but ''man'' has less characters than ''help'')
 +
function man (name)
 +
  help (char (name))
 +
endfunction
 +
 
=C++=
 
=C++=
  

Revision as of 09:44, 2 December 2011

Tiny helper functions

This is a list of tiny helper functions (the equivalent of e.g., shell aliases), the kind one wuld have on its .octaverc file.

replace help with man

If you use octave too much, you'll find yourself trying to use help instead of man on bash. This will allow you to use man in your octave instance (you can also create a help alias for bash but man has less characters than help)

function man (name)
  help (char (name))
endfunction

C++

Real matrix operations

This is a table of matrix operations commonly performed in Octave and their equivalents in C++ when using the octave libraries.

OperationOctaveC++
addA+BA+B
subtractA-BA-B
matrix multiplicationA*BA*B
element multiplicationA.*Bproduct(A,B)
element divisionA./Bquotient(A,B)
transpose*A'A.transpose()
select element m,n of A**A(m,n)A(m-1,n-1)
select row N of A**A(N,:)A.row(N-1)
select column N of A**A(:,N)A.column(N-1)
extract submatrix of AA(a:b,c:d)A.extract(a-1,c-1,b-1,d-1)
absolute value of Aabs(A)A.abs()
comparison to scalar***A>2mx_el_gt(A,2)
A<2mx_el_lt(A,2)
A==2mx_el_eq(A,2)
A~=2mx_el_ne(A,2)
A>=2mx_el_ge(A,2)
A<=2mx_el_le(A,2)
matrix of zerosA=zeros(m,n)A.fill(0.0)
matrix of onesA=ones(m,n)A.fill(1.0)
identity matrixeye(N)identity_matrix(N,N)
inverse of Ainv(A)A.inverse()
pseudoinverse of Apinv(A)A.pseudo_inverse()
diagonal elements of Adiag(A)A.diag()
column vectorA(:)ColumnVector(A.reshape (dim_vector(A.length())))
row vectorA(:)'RowVector(A.reshape (dim_vector(A.length())))
check for Inf or <a href="wiki.pl?NaN">NaN</a>any(~isfinite(A))A.any_element_is_inf_or_nan()
stack two matrices verticallyA=[B;C]B.stack(C)
uniform random matrixrand(a,b)octave_rand::distribution("uniform"); octave_rand::matrix(a,b)
normal random matrixrandn(a,b)octave_rand::distribution("normal"); octave_rand::matrix(a,b)
sum squares of columnssumsq(A)A.sumsq()
sum along columnssum(A,1)A.sum(0)
sum along rowssum(A,2)A.sum(1)
product along columnsprod(A,1)A.prod(0)
product along rowsprod(A,2)A.prod(1)
cumsum along columnscumsum(A,1)A.cumsum(0)
cumsum along rowscumsum(A,2)A.cumsum(1)
cumproduct along columnscumprod(A,1)A.cumprod(0)
cumproduct along rowscumprod(A,2)A.cumprod(1)
number of rowssize(A,1)A.rows()
number of columnssize(A,2)A.cols()

Notes: *Transpose, addition, and multiplication operations also apply to RowVector, ComplexRowVector, ColumnVector, and ComplexColumnVector data types when the dimensions are in agreement. **The difference is due to the fact that arrays are zero-based in C++, but one-based in Octave. ***The names of Octave internal functions, such as mx_el_gt, are not documented and are subject to change. Functions such as mx_el_gt may eventually be available at both the scripting level and in C++ under more common names such as gt.

Complex Matrix Operations

OperationOctaveC++
conjugate tranposeA'A.hermitian()


General

A funny formatting trick with fprintf found by chance

Imagine that you want to create a text table with fprintf with 2 columns of 15 characters width and both right justified. How to do this thing?

That's easy:

If the variable Text is a cell array of strings (of length <15) with two columns and a certain number of rows, simply type for the kth row of Text

fprintf('%15.15s | %15.15s\n', Text{k,1}, Text{k,2});

The syntax '%<n>.<m>s' allocates '<n>' places to write chars and display the '<m>' first characters of the string to display.

Example:

octave:1> Text={'Hello','World'};
octave:2> fprintf('%15.15s | %15.15s\n', Text{1,1}, Text{1,2})
         Hello |           World

Load Comma Separated Values (*.csv) files

A=textread("file.csv", "%d", "delimiter", ",");
B=textread("file.csv", "%s", "delimiter", ",");
inds = isnan(A);
B(!inds) = num2cell(A(!inds))

This gets you a 1 column cell array. You can reshape it to the original size by using the reshapefunction

The next version of octave (3.6) implements the CollectOutput switch as seen in example 8 here: http://www.mathworks.com/help/techdoc/ref/textscan.html

Using Variable Strings in Octave Commands

For example, to plot data using a string variable as a legend:

Option 1 (simplest):

legend = "-1;My data;";
plot(x, y, legend);

Option 2 (to insert variables):

plot(x, y, sprintf("-1;%s;", dataName));

Option 3 (not as neat):

legend = 'my legend';
plot_command = ['plot(x,y,\';',legend,';\')'];
eval(plot_command);

These same tricks are useful for reading and writing data files with unique names, etc.

Vectorizing Tricks

You can easily fill a vector with an index:

   for i=1:n, x(i) = i; end
   x = [1:n];

This works for expressions on the index by wrapping the index in an expression:

   for i=1:n, x(i) = sin(2*pi*i*f/r); end
   x = sin(2*pi*[1:n]*f/r);

You can also work with other vectors this way:

   for i=1:n, x(i) = sin(2*pi*y(i)*f/r); end
   x = sin(2*pi*y*f/r);

Conditionals in the for loop are a little bit tricky. We need to create an index vector for the true condition, and another for the false condition, then calculate the two independently.

   for i=1:n, if y(i)<1, x(i)=y(i); else x(i) = 2*y(i); endif
   idx = y < 1;
   x(idx) = y(idx);
   x(!idx) = 2*y(!idx);

FIXME: add the following

  • examples from matrices
  • tricks with sort and cumsum (e.g., hist, lookup)
  • counter-examples such as a tridiagonal solver
  • sparse matrix tricks
  • tricks relying on fortran indexing

Other references