# Matlab struct vector

(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];
end


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).

• 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. Commented May 18, 2017 at 21:39
• 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. Commented May 18, 2017 at 22:17
• 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. Commented May 18, 2017 at 23:10
• its a finite element code. This "loop" is inside of other loops. For that reason I was looking for the best way to write. Commented May 18, 2017 at 23:48

N = 1e4;