help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: FW: Matrix index, Please e-mail back.


From: Jordi Gutierrez Hermoso
Subject: Re: FW: Matrix index, Please e-mail back.
Date: Tue, 5 Dec 2006 17:39:48 -0600

Sorry... I got a little stubborn about trying to understand this, and
now I think I know how to get what you want.

On 05/12/06, Jorgen Andersson <address@hidden> wrote:
| How would I do what was intended:
|
| 2 4
| 3 8
| 9 3

[from matrix:]

| | a =
| |   1  2  3  4  5
| |   2  3  4  5  6
| |   3  4  5  6  7
| |   9  8  7  6  5
| |   0  3  4  5  6

There are cute little indexing hacks that can be accomplished if you
remember that Octave stores matrices in Fortran column-major order. In
other words, a matrix can be indexed by a single index as if it were
one long vector.

This allows, f'rinstance, with a larger example:

   octave:88> A = zeros(10); #allocate empty 10x10 matrix.
   octave:89> A(:) = [1:100] #Let nth entry of A equal to its single
                             #Fortran-order index.
   A =

        1   11   21   31   41   51   61   71   81   91
        2   12   22   32   42   52   62   72   82   92
        3   13   23   33   43   53   63   73   83   93
        4   14   24   34   44   54   64   74   84   94
        5   15   25   35   45   55   65   75   85   95
        6   16   26   36   46   56   66   76   86   96
        7   17   27   37   47   57   67   77   87   97
        8   18   28   38   48   58   68   78   88   98
        9   19   29   39   49   59   69   79   89   99
      10   20   30   40   50   60   70   80   90  100

   octave:90> i = [2,3,4]' #The search pattern we want.
   i =

     2
     3
     4

   octave:91> j = [0:10:(10-4)*10] #Offset
   j =

      0  10  20  30  40  50  60

   octave:92> j += [0:length(j)-1] #For the specific pattern we want
   j =

      0  11  22  33  44  55  66

   octave:93> [ii, jj] = meshgrid(i,j); #Just a convenient shorthand
   octave:94> A(ii+jj)' #Voila, the elements of A that we sought:
   ans =

      2  13  24  35  46  57  68
      3  14  25  36  47  58  69
      4  15  26  37  48  59  70

Now I think I've got it. I think for a large enough matrix, a method
like this will be faster than for-loops, by replacing for-loops with
two relatively small matrix additions. I hope it does speed up your
code.

(Sorry for chastising you previously for top-posting like that.
I seriously do believe that you should reconsider your
posting style, but I can live with more top-posting if you really want
to keep on doing it.)


HTH,
- Jordi G. H.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]