Tips and tricks: Difference between revisions

1,601 bytes added ,  27 November 2011
+ more tips
(+ general)
(+ more tips)
Line 105: Line 105:
  inds = isnan(A);
  inds = isnan(A);
  B(!inds) = num2cell(A(!inds))
  B(!inds) = num2cell(A(!inds))
B = reshape(B,


This gets you a 1 column cell array. You can reshape it to the original size by using the <code>reshape</function>
This gets you a 1 column cell array. You can reshape it to the original size by using the <code>reshape</function>


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
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
==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===
*MATLAB array manipulation tips and tricks by Peter Acklam: http://home.online.no/~pjacklam/matlab/doc/mtt/index.html
*The MathWorks: Code Vectorization Guide: http://www.mathworks.com/support/tech-notes/1100/1109.html