How to plot a 3D surface with two vectors and one array?

I want to plot a 3D surface , but I cannot apply the surf() command straightforwardly for some reason.
I have two vectors for x and y coordinates. Let us say
x = linspace(-10, 10, 100);
y = linspace(-0.5, 0.5, 100);
To calzulate I have to call some function which works only for fixed values of x and y. Thys, I calculate it as follows
for i = 1 : length(x)
for j = 1 : length(y)
func(i,j) = @MyFunction(__some_parameters__, x(i), y(j));
end
end
As a result I have two vectors for x and y and a matrix of the size length(x)*length(y) for the variable z. Could you tell me please, if there are any convenient methods to rewrite this data to a format that is appropriate for applying the surf() command?
P.S. I used plot3(x(i), y(j), func(i,j), 'b.') with two cycles, but it is a ridiculous "dirty hack" and not a surface.

 Réponse acceptée

Create full vectors of coordinates and arrayfun()
x = linspace(-10, 10, 100);
y = linspace(-0.5, 0.5, 100);
[X, Y] = meshgrid(x, y);
Z = arrayfun(@(xx,yy) sin(xx)+atan2(yy,xx), X, Y);
surf(x, y, Z, 'edgecolor', 'none')

3 commentaires

Bogdan MP
Bogdan MP le 22 Oct 2021
Modifié(e) : Bogdan MP le 22 Oct 2021
Tanhk you. But, unfortunately, it does not applicable to my case (or, at least, I have no idea how to write it correctly). The function I have to call, in fact has the following structure
MyFunc(@OtherFunc, p(1), p(2), .. , p(n), x, y)
here OtherFunc - is some another function of the parameters and . And are just some fixed numbers. This function blows up for some parameters and I accurately control it in a cycle.
Is it possible to reorganise the data itself? Without recalling inner functions? Let's say the only data I have is and an array of .
Well, it looks like I can simply write
surf(x, y, z')
surf(x, y, z')
If that worked for your purposes, then chances are that when you constructed z, you varied x values down columns, and that you varied y values across rows -- that array z(J,K) is a function of x(J), y(K) . That is a very common data organization... but it is not the MATLAB data organization. In MATLAB, up/down (so, along columns) is y, and left/right (so, along rows) is x, and array location z(J,K) is z(y(J), x(K)) .
When you use meshgrid(xvector, yvector), then the coordinates are arranged in such a way that surf(x, y, z) works out.
When you use ndgrid(xvector, yvector) then the coordinates are arranged in such a way that surf(x, y, z) errors (unless xvector and yvector are the same length).
xvec = 1:2; yvec = 1:3
yvec = 1×3
1 2 3
[X, Y] = meshgrid(xvec, yvec)
X = 3×2
1 2 1 2 1 2
Y = 3×2
1 1 2 2 3 3
[X, Y] = ndgrid(xvec, yvec)
X = 2×3
1 1 1 2 2 2
Y = 2×3
1 2 3 1 2 3

Connectez-vous pour commenter.

Plus de réponses (0)

Produits

Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by