Editing Tips and tricks

Jump to navigation Jump to search
Warning: You are not logged in. Your IP address will be publicly visible if you make any edits. If you log in or create an account, your edits will be attributed to your username, along with other benefits.

The edit can be undone. Please check the comparison below to verify that this is what you want to do, and then publish the changes below to finish undoing the edit.

Latest revision Your text
Line 1: Line 1:
==Preferences==
=C++=
Sometimes, Octave defaults are not the best for someone's specific use. To change the defaults, use the following on the {{Path|[[.octaverc]]}} file.
 
=== Changing default figure size ===
The default size of a figure may be appropriate for simple figures but not so much when using {{Codeline|subplot}} for example. This can be changed though.
 
{{Code|change default figure size|<pre>set (0, 'DefaultFigurePosition', [1 get(0, "screensize")(4:-1:3) get(0, "DefaultFigurePosition")(4)]);</pre>}}
 
The value of {{Codeline|DefaultFigurePosition}} must be a four element vector with the x and y coordinates for the figure, followed by its width and height. The code above sets the default image to be placed at the top of the monitor, with the width of the monitor and the same height previously set as default.
 
=== Changing default font for axes ===
 
To display tex characters such as '\alpha' or '\lambda', a TrueType font ("arial" for instance) is better for the gnuplot backend [https://savannah.gnu.org/bugs/?30681]
{{Code|change default axes font name|<pre>set (0, "DefaultAxesFontName", "Arial")</pre>}}
It can then be necessary to change the font size as well
{{Code|change default axes font size|<pre>set(0, 'DefaultAxesFontSize', 10)</pre>}}
 
 
=== Shorten help message ===
To get rid of the long help message with the link to the Octave homepage place this in your startup file usually at ~/.octaverc (if it does not exist, create it). See the [http://www.gnu.org/software/octave/doc/interpreter/Startup-Files.html documentation] for more information.
suppress_verbose_help_message(1)
 
==Tiny helper functions==
 
This is a list of tiny helper functions (the equivalent of e.g., shell aliases), the kind one would have on its {{Path|.octaverc}} file.
 
=== Reload 'octave.rc' after 'clear' ===
When using {{Codeline|clear}}, one may accidentally remove functions (alias) or other variables set on the {{Path|octave.rc}} file. This can fixed by shadowing the {{Codeline|clear}} function with the following:
 
{{Code|reload octave.rc after clear|<pre>
function clear (varargin)
  args = sprintf (', "%s"', varargin{:});
  evalin ("caller", ['builtin ("clear"' args ')']);
  source ("~/.octaverc");
endfunction</pre>}}
 
The problem with this approach is if there's path manipulation on the {{Path|octave.rc}} file, such as {{Codeline|addpath}}. A workaround is needed for each case since it is not possible to obtain a reliable list of what's in Octave load path. But basically should be to undo what the file does, before {{Codeline|source ("~/.octaverc")}}.
 
If there's a {{Codeline|pkg unload all}} on it, this would also unload all packages. The following adjustment will keep the packages loaded
 
{{Code|reload octave.rc after clear but keep packages loaded|<pre>
function clear (varargin)
  args = sprintf (', "%s"', varargin{:});
  evalin ("caller", ['builtin ("clear"' args ')']);
  pkglist = pkg ("list");
  loadedpkg = cell (0);
  for ii = 1:numel (pkglist)
    if (pkglist{ii}.loaded)
      loadedpkg{end+1} = pkglist{ii}.name;
    endif
  endfor
  source ("~/.octaverc");
  if (numel (loadedpkg) != 0)
    pkg ("load", loadedpkg{:});
  endif
endfunction</pre>}}
 
 
=== replace help with man ===
 
If you use octave too much, you'll find yourself trying to use {{Codeline|help}} instead of {{Codeline|man}} on bash. This function will fix that so you can use {{Codeline|man}} in your octave instance (you can also do the opposite, create a {{Codeline|help}} alias in bash but {{Codeline|man}} has fewer characters).
 
{{Code|alias to help|<pre>
function man (name)
  help (char (name))
endfunction</pre>}}
 
==C++==
 
=== Real matrix operations===


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


Line 78: Line 10:
<tr><td>element multiplication</td><td><code>A.*B</code></td><td><code>product(A,B) </code></td></tr>
<tr><td>element multiplication</td><td><code>A.*B</code></td><td><code>product(A,B) </code></td></tr>
<tr><td>element division</td><td><code>A./B</code></td><td><code>quotient(A,B) </code></td></tr>
<tr><td>element division</td><td><code>A./B</code></td><td><code>quotient(A,B) </code></td></tr>
<tr><td>transpose*</td><td><code>A.'</code></td><td><code>A.transpose()</code></td></tr>
<tr><td>transpose*</td><td><code>A'</code></td><td><code>A.transpose()</code></td></tr>
<tr><td>select element m,n of A**</td><td><code>A(m,n)</code></td><td><code>A(m-1,n-1)</code></td></tr>
<tr><td>select element m,n of A**</td><td><code>A(m,n)</code></td><td><code>A(m-1,n-1)</code></td></tr>
<tr><td>select row N of A**</td><td><code>A(N,:)</code></td><td><code>A.row(N-1)</code></td></tr>
<tr><td>select row N of A**</td><td><code>A(N,:)</code></td><td><code>A.row(N-1)</code></td></tr>
Line 98: Line 30:
<tr><td>column vector</td><td><code>A(:)</code></td><td><code>ColumnVector(A.reshape (dim_vector(A.length())))</code></td></tr>
<tr><td>column vector</td><td><code>A(:)</code></td><td><code>ColumnVector(A.reshape (dim_vector(A.length())))</code></td></tr>
<tr><td>row vector</td><td><code>A(:)'</code></td><td><code>RowVector(A.reshape (dim_vector(A.length())))</code></td></tr>
<tr><td>row vector</td><td><code>A(:)'</code></td><td><code>RowVector(A.reshape (dim_vector(A.length())))</code></td></tr>
<tr><td>check for Inf or NaN</td><td><code>any(~isfinite(A))</code></td><td><code>A.any_element_is_inf_or_nan()</code></td></tr>
<tr><td>check for Inf or <a href="wiki.pl?NaN">NaN</a></td><td><code>any(~isfinite(A))</code></td><td><code>A.any_element_is_inf_or_nan()</code></td></tr>
<tr><td>stack two matrices vertically</td><td><code>A=[B;C]</code></td><td><code>B.stack(C)</code></td></tr>
<tr><td>stack two matrices vertically</td><td><code>A=[B;C]</code></td><td><code>B.stack(C)</code></td></tr>
<tr><td>uniform random matrix</td><td><code>rand(a,b)</code></td><td><code>octave_rand::distribution("uniform"); octave_rand::matrix(a,b)</code></td></tr>
<tr><td>uniform random matrix</td><td><code>rand(a,b)</code></td><td><code>octave_rand::distribution("uniform"); octave_rand::matrix(a,b)</code></td></tr>
Line 113: Line 45:
<tr><td>number of rows</td><td><code>size(A,1)</code></td><td><code>A.rows()</code></td></tr>
<tr><td>number of rows</td><td><code>size(A,1)</code></td><td><code>A.rows()</code></td></tr>
<tr><td>number of columns</td><td><code>size(A,2)</code></td><td><code>A.cols()</code></td></tr>
<tr><td>number of columns</td><td><code>size(A,2)</code></td><td><code>A.cols()</code></td></tr>
<tr><td>range</td><td><code>0.1:0.2:0.9</code></td><td><code>Range (0.1, 0.9, 0.2).matrix_value ()</code></td></tr>
</table>
</table>


Notes:
Notes:
<nowiki>
*Transpose, addition, and multiplication operations also apply to RowVector, ComplexRowVector, ColumnVector, and ComplexColumnVector data types when the dimensions are in agreement.


* 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 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.
 
</nowiki>
* 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===


==Complex Matrix Operations==
<table>
<table>
<tr><td><b>Operation</b></td><td><b>Octave</b></td><td><b>C++</b></td></tr>
<tr><td><b>Operation</b></td><td><b>Octave</b></td><td><b>C++</b></td></tr>
Line 131: Line 62:
</table>
</table>


==General==
===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
=General=
*examples from matrices
==How to declare functions inside a test block==
*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====
function experience
%!test
%! experience_design_mat
%! experience_obs_eqs
%! assert (experience_design_mat == pi);
%! assert (experience_obs_eqs == exp(1));
%!
%! endfunction  % this is a trick.
%! % now we can declare functions to be used by the test above.
%!
%! function a = experience_design_mat
%!    a = pi;
%! endfunction
%!
%! function b = experience_obs_eqs
%!    b = exp(1);
%! % endfunction: don't add it here. Let test() do it.


*MATLAB array manipulation tips and tricks by Peter Acklam: https://web.archive.org/web/20151030212438/http://home.online.no/~pjacklam/matlab/doc/mtt/index.html
==A funny formatting trick with fprintf found by chance==
*The MathWorks: Code Vectorization Guide: http://www.mathworks.com/support/tech-notes/1100/1109.html


[[Category:Tips and tricks]]
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?


===Changing BLAS===
That's easy:


Many Octave functions are wrappers to optimized numerical libraries, notably BLAS and ATLAS. It is possible to achieve impressive performance gains by simply using a library tuned to your platform. One example is using OpenBLAS to replace the default BLAS implementation ([https://web.archive.org/web/20140217072457/http://www.stat.cmu.edu/~nmv/2013/07/09/for-faster-r-use-openblas-instead-better-than-atlas-trivial-to-switch-to-on-ubuntu/ further details]).
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.


On some Linux distributions, this just takes a few commands. For instance, on Ubuntu, it usually suffices to run
Example:
octave:1> Text={'Hello','World'};
octave:2> fprintf('%15.15s | %15.15s\n', Text{1,1}, Text{1,2})
          Hello |          World


sudo apt-get install libopenblas-base libatlas3gf-base
==Load Comma Separated Values (*.csv) files==


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


sudo update-alternatives --config libblas.so.3
This gets you a 1 column cell array. You can reshape it to the original size by using the <code>reshape</function>


and then selecting the openblas option.
The next version of octave (3.6) implements the <code>CollectOutput</code> switch as seen in example 8 here:                    http://www.mathworks.com/help/techdoc/ref/textscan.html
Please note that all contributions to Octave may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see Octave:Copyrights for details). Do not submit copyrighted work without permission!

To edit this page, please answer the question that appears below (more info):

Cancel Editing help (opens in new window)

Templates used on this page: