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: John W. Eaton
Subject: Re: slow 'eval' function - maybe pointers would do?
Date: Fri, 30 Oct 2009 09:38:39 -0400

On 30-Oct-2009, Guido Walter Pettinari wrote:

| 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 think that's what the above code does.  It doesn't create many
structures.

Here's a complete working example:

  for ii = 1:4
    names{ii}  = sprintf ("ks_%d", ii);
    values{ii} = rand (3, 1);
  endfor

  S = cell2struct (values, names, 2)

Does that help?  You don't need eval to do this job.

| 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?

The variable ii is not a string, so [ 'ks_', ii ] doesn't work.  You
have to convert the number to a string.  It looks better to me to
write it as sprintf ('ks_%d', ii) instead of ['ks_', num2str(ii)].

jwe


reply via email to

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