Note that there are some explanatory texts on larger screens.

plurals
  1. POOctave and Matlab "wat" matrix/vector inconsistencies
    primarykey
    data
    text
    <p>I've noticed various cases in Matlab and octave where functions accept both matrices and vectors, but doesn't do the same thing with vectors as it does with matrices.</p> <p>This can be frustrating because when you input a matrix with a variable number of rows/columns, it could be interpreted as a vector and do something you don't expect when the height/width is 1 making for difficult debugging and weird conditional edge cases.</p> <p>I'll list a few I've found, but I'm curious what others people have run into</p> <p>(Note: I'm only looking for cases where code accepts matrices as valid input. Anything that raises an exception when a non-vector matrix is given as an argument doesn't count)</p> <p>1) "diag" can be used to mean diagonal of a matrix or turn a vector into a diagonal matrix</p> <p>Since the former is generally only used for square matrices this isn't so egregious in matlab, but in Octave it can be particularly painful when Octave interperets a vector beginning with a nonzero element and everything else zeros as a "diagonal matrix" ie</p> <pre><code>t=eye(3); size(diag(t(:,3))) == [3,3] size(diag(t(:,2))) == [3,3] size(diag(t(:,1))) == [1,1] </code></pre> <p>2) Indexing into a row-vector with logicals returns a row-vector</p> <p>Indexing into anything else with logicals returns a column vector</p> <pre><code>a = 1:3; b = true(1,3); size(a(b)) == [1, 3] a = [a; a]; b = [b; b]; size(a(b)) == [6, 1] </code></pre> <p>3) Indexing into a vector v with an index vector i returns a vector of the same (row/col) type as v. But if either v or i is a matrix, the return value has the same size as i.</p> <pre><code>a = 1:3; b = a'; size(a(b)) == [1, 3] b = [b,b]; size(a(b)) == [3, 2] </code></pre> <p>4) max, min, sum etc. operate on the columns of a matrix M individiually unless M is 1xn in which case they operate on M as a single row-vector</p> <pre><code>a = 1:3 size(max(a)) == [1, 1] a = [a;a] size(max(a)) == [1, 3] </code></pre> <p>max is particularly bad since it can't even take a dimension as an argument (unlike sum)</p> <p>What other such cases should I watch out for when writing octave/matlab code?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload