help-octave
[Top][All Lists]
Advanced

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

Re: reference an index and use it as part of names


From: Jordi Gutiérrez Hermoso
Subject: Re: reference an index and use it as part of names
Date: Wed, 21 Aug 2013 20:57:52 -0400

On 21 August 2013 18:30, jacopo rocchi <address@hidden> wrote:
> Hello,
> I have many array indexed like this:
> v1
> v2
> v3
> and so on.
> Is it possible to handle them in a for like this:
>
> for i=1:N
> operations on v_i
> end

This is one of the strangest recurrent questions we get. I do wonder
where it comes from, and I should write about it for our FAQ.

So, the answer is, use a real index. The Octave language has indices,
so use them.

Instead of doing

   v1 = this();
   v2 = that();
   v3 = those();

Do

   v(1) = this();
   v(2) = that();
   v(3) = those();

This is assuming that the `this`, `that`, and `those` functions all
return scalars. If they return more complex things, like matrices or
strings, you may want instead to use a cell array:

    v{1} = this();
    v{2} = that();
    v{3} = those();

Then you can loop over your vector items like this:

   for i = 1:length(v)
     v(i) = these(i);
   endfor

or using v{i} instead in the case of cell array. However, also
consider this before looping:

    
https://www.gnu.org/software/octave/doc/interpreter/Vectorization-and-Faster-Code-Execution.html

What you should NOT do, which almost everyone does after they've
created variables named like v1, v2, v3, is to play silly tricks with eval and
sprintf or cat:

    for i = 1:3
      eval(sprintf("v(%d) = these(%d);",1,1));
    endfor

or even worse:

    for i = 1:3
      eval(["v(", num2str(i), ") = these(", num2str(i), ");]);
    endfor

HTH,
- Jordi G. H.


reply via email to

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