Calculating 3D matrix

2 Ansichten (letzte 30 Tage)
zkhan1
zkhan1 am 25 Okt. 2017
Kommentiert: zkhan1 am 25 Okt. 2017
Hi all, I want to calculate a 3D matrix comprising of distances from a 128 elements array(lying along x_axis) to a 2D plane of pixels with dimensions 300*200. The resultant distance matrix must have the dimensions 128*300*200. 300 is the number of pixels along z_axis and 200 are the number of pixels in x_axis. This can easily be done with 3 nested loops but I wonder if someone would please help without using any loop or with one loop at most. Appreciate your help. Thanks
  1 Kommentar
Rik
Rik am 25 Okt. 2017
I don't entirely understand what you mean, but I think this can be done without any loops. The solution would probably involve the meshgrid function.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Cam Salzberger
Cam Salzberger am 25 Okt. 2017
It's not totally clear what is meant by "distances". Typically when you want "distances", you are doing some computation between points with at least two coordinates. On the other hand, your desired output seems to mean you want to compare the value at every point in your vector to every other point in the array, resulting in the 3-D array containing the "difference" between every possible combination.
Since R2016b (with implicit expansion), this becomes pretty trivial using reshape. Here's a quick example:
mtrx = rand(3, 2);
arr = rand(4, 1);
reshapedMtrx = reshape(mtrx, [1 size(mtrx)]);
dist = arr-reshapedMtrx;
In previous releases, you'd likely want to play with repmat to get both operands to the output array size.
-Cam
  1 Kommentar
zkhan1
zkhan1 am 25 Okt. 2017
Thanks Cam for your answer. Let me explain my question by an example.
x_elem = [-4 2 0 2 4]; % x_coordinates of the elements in array
y_elem = zeros(1,5);
z_elem = zeros(1,5);
x_axis = [-4 2 0 2 4]; % x_coordinates of the field
y_axis = zeros(1,5);
z_axis = [5 6 7 8 9 10]; % z_coordinates of the field
Now since I have coordinates of the elements as well as the field, I need to find distances from each element to each field point using the distance formula, and the resultant matrix would be 6*5*5, where 6 is the number of rows, 5 is number of columns and the last 5 is the number of elements.
My solution: I first calculated distances of all points in first column of the field from all elements (6*5 matrix) and then looped it to do the same for all 5 columns. Wonder if the loop can be avoided? I used both repmat and meshgrid.
Thanks once again for your help

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by