(I resume my question with a simple example) I want to create a struct in matlab/octave as follows

c(1).x   = [0  1];
c(2).x   = [0  1];
c(100).x = [0  1];

One way is to do an for cycle:

for i=1:100
   c(i).x = [0 1];

My question is, how can avoid the cycle for? (The reason is that everybody knows that we need to avoid the for cycles on matlab).

  • 5
    $\begingroup$ The reason people usually avoid for cycles is because of the overhead compared to direct array manipulation. There is no vectorized form of this, unless you, say, replace c.x it with a $100\times2$ matrix. The way you've done this, you already have quite a lot of overhead, with a 100 structures and a 100 small arrays, so eliminating the for loop just isn't important. $\endgroup$
    – Kirill
    May 18, 2017 at 21:39
  • $\begingroup$ the size of each vector c(i).x, with i=1:100 (really, I have i=1:10e4 or more), its very different (en my problem, not in the example that I showed) and, in addition, just some of them increasing during the program. For that reason I though its a good idea to have 100 structures. $\endgroup$
    – yemino
    May 18, 2017 at 22:17
  • 1
    $\begingroup$ I think it's quite likely that if you can afford the overhead of $10^4$ structures, then a simple for-loop is not expensive enough to worry about. Have you actually tried profiling your code and making sure that it is in fact a problem? It would be nice to see some actual timing data. $\endgroup$
    – Kirill
    May 18, 2017 at 23:10
  • $\begingroup$ its a finite element code. This "loop" is inside of other loops. For that reason I was looking for the best way to write. $\endgroup$
    – yemino
    May 18, 2017 at 23:48

1 Answer 1


You can do something like this in Matlab:

N = 1e4;
c = []; c.x = [0 1]; 
c(1:N) = c;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.