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

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

Opportunities for recent engineering grads.

# Is there a shorter/smarter way to do this code

Asked by Itzik on 7 Nov 2012

Hi, I am trying to creat a matrix of all possible coordinates given 2 coordinate vectors. my code is attached below. I know there is a better way to do this. can anyone help?

``` n=8 %can be any number
Ycoord=[0.5:n-0.5];
Xcoord=[0.5:n-0.5];
for i=1:n
for j=1:n
handles.coordinates{i,j}={Xcoord(i),Ycoord(j)};
end
end```

thanks

## Products

No products are associated with this question.

Answer by Jan Simon on 7 Nov 2012
Edited by Jan Simon on 7 Nov 2012

No, there is no "better" way, as long as you want to store the data in a cell array. You could use mat2cell, but then the same loops are performed inside this function also. One small improvement is to omit the unnecessary square brackets around the vectors (MLint should mention this already):

```Ycoord = 0.5:n-0.5;
Xcoord = 0.5:n-0.5;
```

If you could store the values in a numerical array, simplifications are possible:

```nX = length(Xcoord);
nY = length(Ycoord);
handles.coordinates = cat(3, repmat(Ycoord, nX, 1), repmat(Xcoord', 1, nY));
```

Then an pair of coordinates is restored by:

```C = squeeze(handles.coordinates(i, j, :));
```