MATLAB Answers

## Preallocating the size of a matrix which concatenates horizontally matrices in a for loop

Asked by Giorgos Papakonstantinou

### Giorgos Papakonstantinou (view profile)

on 16 Jun 2013
Accepted Answer by the cyclist

### the cyclist (view profile)

How can I preallocate matrix t:

```t=[];
```
```for i=1:3;
a=randi(10,3,2);
```
`      t=[a t];`
```end
```

## Products

No products are associated with this question.

## 1 Answer

### the cyclist (view profile)

Answer by the cyclist

### the cyclist (view profile)

on 16 Jun 2013
Accepted answer

Like this. (I also parameterized so it would be easier to see how this generalizes.)

```m=3;
n=2;
```
```t = zeros(m,m*n);
```
```for i=1:m;
a = randi(10,m,n);
t(:,n*(i-1)+1:n*i) = a;
end
```

You don't need the intermediate variable, either:

```m=3;
n=2;
```
```t = zeros(m,m*n);
```
```for i=1:m;
t(:,n*(i-1)+1:n*i) = randi(10,m,n);
end
```

#### 1 Comment

Giorgos Papakonstantinou

### Giorgos Papakonstantinou (view profile)

on 16 Jun 2013

Thank you cyclist.

#### Join the 15-year community celebration.

Play games and win prizes!

Learn more

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

### Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

### MATLAB Academy

New to MATLAB?

Learn MATLAB today!