Thus A(:, 2) gives us matrix which is 2nd column of A, A(:, 2:4) gives us matrix with columns of A from 2 to 4, same is accomplished with A(:, ), and A(:, ) selects 1st, 4th and 9th columns of A. This will extract elements from A: all for rows and precisely right columns. Now, we just plug our original vector y into column index of matrix A. What just happened: first we created an identity matrix A of size 10 – note that it consists of exactly 10 vectors we are mapping to and each is in right column position. If you never worked with Octave before then solution may amaze you, if you did then this might be your normal routine: Then given some vector y like above (where each element is a number from 1 to 10) we want to produce series of vectors that correspond to elements in y. Thus, 1 corresponds to vector (1 0 0 0 0 0 0 0 0 0), 2 corresponds to vector (0 1 0 0 0 0 0 0 0 0) and so on until 10 that corresponds to (0 0 0 0 0 0 0 0 0 1). Let’s say each number from 1 to 10 corresponds to 10-dimensional vector of 0s and 1 with all of its elements set to 0 except the position of the number. Then I used function repmat to make vector y 10 times its original length by repeating it 10 times (which results in 1 by 100 matrix y). Suppose I have a row vector (we may call it also an array but ultimately it is a single row matrix) of numbers from 1 to 10:įunction randperm returned a row vector containing random permutation of numbers 1 through 10. Matrix magicThis example illustrates why and how things may work out better without control statements in Octave. What just happened: function size returned 1st dimension of array X (number of rows) then function ones generated a vector (2d dimension is 1) of 1s, and finally we concatenated column and X. Then I just concatenate a vector of 1s of proper size and X: Suppose you have a matrix X and you need to insert a column of 1s in front. The reason are many matrix operators and functions Octave offers may accomplish a task without ever invoking a single control statement in a fraction of time. In Octave for any given problem there is higher than 50% chance that using matrices alone solves the problem with less code and more efficiently than when using loop and condition statements. Being a high level language Octave has control statements if, switch, loops for and while but using them in Octave is often your second choice. To stir things up a bit I make the following claim: Use special functions to define special matrices, e.g. Matrices and VectorsCreating vector or matrix in Octave is simple: Just these by themselves are worth a whole book on Octave but instead I go on with few cool examples (leaving the book for later :-).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |