help-octave
[Top][All Lists]
Advanced

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

Re: slow 'eval' function - maybe pointers would do?


From: Carlo de Falco
Subject: Re: slow 'eval' function - maybe pointers would do?
Date: Thu, 29 Oct 2009 20:37:06 +0100


On 29 Oct 2009, at 18:52, Guido Walter Pettinari wrote:

Hi everybody!

I need to assign values to a series of variables with numbered names,
such as

ks_1 = ... ;
ks_2 = ... ;
...
ks_N = ... ;

where N is big and is determined at runtime. I do not want to use a
vector named 'ks' such that ks(i) = ks_i and so on. Therefore, I used
the 'eval' function in this way:

for i=1:N
   eval ( [ 'k', int2str(i), ' = ... ;' ] );
endfor

However, using 'eval' the execution time of my loop increases ~6 fold.
To test this behaviour, please try to run the following script:

tic();
for i=1:100000   sin(2);   endfor
toc()

tic();
for i=1:100000   eval ( 'sin(2);' );   endfor
toc()

On my machine, the output is:

Elapsed time is 0.8 seconds.
Elapsed time is 5 seconds.

Could you please suggest a more performance-friendly workaround?
Actually, my numbered variables are fields of a structure (es.
struct.k_1, struct.k_2 ... ); I thought that one could solve the
problem by using pointers to access them, but I could not find support
for pointers in Octave.

Thank you,

Guido


You can do what you ask by:

for ii = 1:N
names{ii}  = sprintf("ks_%d", ii);
values{ii} = somehow_compute_value (ii);
endfor

S = cell2struct (values, names, 2)

but what is the reason why you don't want to just use

for ii = 1:N
ks{ii}  = somehow_compute_value (ii);
endfor

?

c.



reply via email to

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