## How to transform a XYZ-Array into a XxY-Matrix with Z as values of each Mxy-Component and vice versa?

Asked by Emerson De Souza

on 18 Nov 2012

### Chad Greene (view profile)

on 6 Apr 2016
Accepted Answer by Walter Roberson

### Walter Roberson (view profile)

Hi, I have a table XYZ with three columns (xyz) as below:

```1	1	1
1	2	2
1	3	3
2	1	4
2	2	5
2	3	6
3	1	7
3	2	8
3	3	9
```

and I want to transform it into a Mxy-Matrix with Z as value for each Mxy pair as follows:

```1	4	7
2	5	8
3	6	9
```

On the other hand I may have directly the Matrix Mxy and would like to obtain the XYZ-table.

I already tried mesh, meshgrid, ndgrid, surf and etc... as documented, but nothing worked as I wished. It is possible that I did not understand yet how to use this commands.

I wonder if someone could tell me how to write the command to convert:

1) Table XYZ to Matrix Mxy with Z as values of each Mxy-pair 2) Matrix Mxy to Table XYZ

I thank you in advance for your help

Emerson

## Products

### Walter Roberson (view profile)

Answer by Walter Roberson

### Walter Roberson (view profile)

on 18 Nov 2012

```accumarray(XYZ(:,[2 1]), XYZ(:,3)]
```

Emerson De Souza

### Emerson De Souza (view profile)

on 18 Nov 2012

Thank you Walter, your suggestion works fine as below

```xvector = 1:1:3;
yvector = 1:1:3;
numX = numel(xvector);
numY = numel(yvector);
yvector = repmat(yvector(:),numX,1);
xvector = repmat(xvector   ,numY,1);
XY = [xvector(:) yvector];
Z=(1:1:length(XY))';
```
```XYZ=[XY Z];
M=accumarray(XYZ(:,[2 1]), XYZ(:,3));
```

Now, if M is given, how do I obtain XYZ?

Thank you in advance

Emerson

Walter Roberson

### Walter Roberson (view profile)

on 18 Nov 2012
```[X,Y] = ind2sub(size(M), 1:numel(M));
XYZ = [X(:), Y(:), M(:)];
```
Emerson De Souza

### Emerson De Souza (view profile)

on 19 Nov 2012

Thank you Walter, your suggestions fixed my problem. Wish you a nice day

Emerson

### Chad Greene (view profile)

on 6 Apr 2016

Thanks to Walter's excellent suggestion to use accumarray, I wrote an xyz2grid function to do this for GMT data.

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

Play games and win prizes!

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