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: Guido Walter Pettinari
Subject: Re: slow 'eval' function - maybe pointers would do?
Date: Fri, 30 Oct 2009 12:27:20 +0000

Hi!

Thank you for the answers, Judd & Carlo!

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)


You are right, but the point is that in my code each 'ks_i' is a vector of M elements. I am filling all the 'ks_i' vectors inside a 'for i=1:M; for i=1:N' nested loop. If I were to call 'cell2struct' in each sub-loop, I will obtain many structs, while my idea is to store the data in a single struct. I want to obtain a struct 's' such that each field 's.ks_i' contains a Mx1 vector (where M is big).

By the way, I solved the issue by memorizing the 'ks_i' into a MxN vector called 'ks' inside the loop. Once outside the loop, I filled the struct in this way:

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

In this way I use more memory but the execution is faster.

Thank you,

Guido

P.S. Carlo, is there any reason whereby in your example you used sprintf instead of the string concatenation operator [ 'ks_', ii ] ? Is the former faster?


On Oct 29, 2009, at 19:37 , Carlo de Falco wrote:


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]