Matrix of pairs from two arrays in matlab
-
06-06-2021 - |
Domanda
I have a couple of arrays:
x = [0:pi/16:2*pi]
y = [0:pi/16:2*pi]
And I want to make a matrix xy in this way:
xY = [(0,0) (0,pi/16) ... (0,2pi);
(pi/16,0) (pi/16,pi/16) ... (pi/16,2pi);
: : :
(2pi,0) (2pi,pi/16) ... (2pi,2pi)]
I've tried many things like this:
for i=1:length(x)
for j=1:length(y)
xy{i,j} = [{x(i),y(j)}];
end
end
, but I have encountered many errors.
I know it should be easy, and the biggest problem is that the title of my post (and because of that, the way I'm looking for help) is wrong, so I apologize for that.
I think I should mention that I'm trying to create a multi-layer perceptron that will get trained with that matrices and this formula:
fxy = cos(x)-3*sin(y);
Thanks in advance!
Soluzione
This is exactly what meshgrid
is designed for.
Altri suggerimenti
The simplest way is to this is to create matrix of size length(x)
-by-length(y)
-by-2
:
A = zeros(length(x), length(y), 2);
for i = 1 : length(x); for j = 1 : length(y); A(i, j, :) = [x(i), y(j)]; end; end;
In your case, matrix A
will have size 33x33x2
. To get pair using indexes i, j
use the following code:
squeeze(A(i, j, :))
Or you can adjust your code to work with such 3-dimensional matrix.