# use x,y,z coordinates from 3D matrix and store the result in new 3D matrix

65 views (last 30 days)
Hyukjin Jang on 23 Feb 2021
Commented: Benjamin Kraus on 23 Feb 2021
I'm trying to use x,y,z coordinates from 3D matrix to find values from a equation and store the results in new 3D matrix.
To explain it very simple,
let's say I have created a 3D matrix with following x,y,z arrays.
x = [0.00001:0.00001:0.1];
y = [0.00001:0.00001:0.1];
z = [0.00001:0.00001:0.1];
A = cat(3,x,y,z);
Then, I want to use all coordinates from 3D matrix to solve K = X+Y+Z and store values into new 3D matrix, K.
##### 2 CommentsShowHide 1 older comment
Rik on 23 Feb 2021
Your grid is too fine to have a workable grid:
x = 0.00001:0.00001:0.1;
y = 0.00001:0.00001:0.1;
z = 0.00001:0.00001:0.1;
[X,Y,Z]=ndgrid(x,y,z);
Error using repmat
Requested 10000x10000x10000 (7450.6GB) array exceeds maximum array size preference. Creation of arrays greater than this limit may take a long time and cause MATLAB to become unresponsive.

Error in ndgrid (line 72)
varargout{i} = repmat(x,s);
While there are machines with 7TB of RAM, there aren't many of them, and they don't have it in a continuous block (which is what Matlab needs).
Is this indeed what you wanted to do? Follow this up with something like V=X*2+Y/3+Z.^2;?

Benjamin Kraus on 23 Feb 2021
Edited: Benjamin Kraus on 23 Feb 2021
You have three options:
1. Split the matrix apart again before operating on it.
2. Operation on "slices" of the matrix using indexing.
3. Use a function that takes a dimensions input.
Option 1:
x = A(:,:,1);
y = A(:,:,2);
z = A(:,:,3);
K = x + y + z;
Option 2:
K = A(:,:,1) + A(:,:,2) + A(:,:,3);
Option 3:
K = sum(A,3);
##### 2 CommentsShowHide 1 older comment
Benjamin Kraus on 23 Feb 2021
After reading Rik's response I may have misunderstood your questions. I was assuming that you wanted to perform an element-by-element operation on each of the vectors... in your case adding the first element of each vector, then adding the second element of each vector, then adding the third element, etc.
However, I suspect you wanted to perform some math on all combinations of each vector (add the first element of X with all the elements of Y and Z, not just the first).
Assuming you handle the memory issue Rik identified, you don't want to use the cat to merge your input vectors. Instead, you can either use something like meshgrid or ndgrid to convert X, Y, and Z individually into 3D matrices, or you can use implicit scalar expansion (see the "Add Row and Column Vector" example on this doc page, or check out this blog post).
For example:
X = (1:10)'; % column vector
Y = 11:15; % row vector
Z = reshape(21:27,[1 1 7]); % "page" vector
K = 2.*X + 3.*Y + 4.*Z; % 3D matrix
Alternatively, using ndgrid:
[X,Y,Z] = ndgrid(1:10,11:15,21:27);
K = 2.*X + 3.*Y + 4.*Z;