Help: Converting 3D Data into a 3D Matrix More Efficiently
1 view (last 30 days)
Show older comments
Hello,
I use mainly use MATLAB for data analysis/plotting and, recently, I ran into a little coding problem.
The data that I work with is in the following format:
x1 y1 z1 a1
x2 y1 z1 a2
x3 y1 z1 a3
x1 y2 z1 a4
x2 y2 z1 a5
x3 y2 z1 a6
...
where x y z represent the coordinates and a is the variable of interest.
What I wish to do is to convert this data into a 3D matrix that only contains a's. Let's call this matrix A.
The end matrix will be of dimension Nx by Ny by Nz, where Nx, Ny, and Nz represent the number of unique x, y, and z locations, respectively.
There are no voids in a, meaning for every combination of unique x, y, and z, there is an associated value a.
For example, if I had two unique x locations, three unique y locations, and four unique z locations, A should be 2x3x4. Basically, if I call A(2,2,3), I'm calling the value a at (x2, y2, z3).
The code I have now does what I want it to do; however, it is terribly inefficient and time consuming as you can see below. I was wondering if you guys could help me write a better code. I feel like there is already a code out there that does this but I couldn't find any. I feel like there's a built in code that does this but I don't know what to search for either.
This is what I have so far:
% data is a 27x4 matrix. Columns represent: x, y, z, and a
% x, y and z each have 3 unique location values. Hence, 27 rows.
% 3x3x3 was chosen for the sake of simplicity for this problem
x = unique(data(:,1));
y = unique(data(:,2));
z = unique(data(:,3));
a = data(:,4);
Nx = length(x);
Ny = length(y);
Nz = length(z);
Na = length(a);
% Build matrix A
A = zeros(nx,ny,nz);
for nd = 1:Na
for i = 1:Nx
for j = 1:Ny
for k = 1:Nz
if x(i) == data(nd,1) && y(j) == data(nd,2) && z(k) == data(nd,3)
A(i,j,k) = a(nd);
end
end
end
end
end
Any help is greatly appreciated!
Sincerely,
DB
0 Comments
Answers (1)
Walter Roberson
on 4 Sep 2015
[x, xidx] = unique(data(:,1));
[y, yidx] = unique(data(:,2));
[z, zidx] = unique(data(:,3));
a = data(:,4);
nx = length(x);
ny = length(y);
nz = length(z);
A = zeros(nx, ny, nz, class(a));
A( sub2ind([nx, ny, nz], xidx(:), yidx(:), zidx(:)) ) = a;
0 Comments
See Also
Categories
Find more on Numeric Types in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!