I am trying to compute the gradient of a 3-D matrix using MATLAB (version 2016a). If I type "help gradient" it says the following:
"HX and HY can either be scalars to specify
the spacing between coordinates or vectors to specify the
coordinates of the points. If HX and HY are vectors, their length
must match the corresponding dimension of F." (emphasis mine).
Here is a sample code:
x = 1:30; nx = length(x);
y = 1:62; ny = length(y);
z = 1:23; nz = length(z);
F = rand(nx,ny,nz);
[FX,FY,FZ] = gradient(F,x,y,z);
Here, I am inputting vectors x, y, and z to compute the gradient. These are vectors and it says in the help that HX and HY must have a length matching the corresponding dimension of F. The x-dimension of F has length nx. So the x vector also has length nx. It should work, according to the help.
However, I get an error:
Index exceeds matrix dimensions.
Error in gradient (line 112)
h = h(3:n) - h(1:n-2);
When I dig a little deeper into the "gradient" function I come across this line in the "parse_inputs" embedded function:
% Swap 1 and 2 since x is the second dimension and y is the first.
loc = v;
if ndim > 1
loc(2:-1:1) = loc(1:2);
end
What is going on here?
Why does MATLAB swap the x and y dimensions?
If I do the following code and swap the x and y vectors, then the code works.
x = 1:30; nx = length(x);
y = 1:62; ny = length(y);
z = 1:23; nz = length(z);
F = rand(nx,ny,nz);
[FX,FY,FZ] = gradient(F,y,x,z);
I just don't understand why. I've looked around on stack overflow but can't find any answer to the question.
In any case, it seems that the help is somewhat misleading because you actually need to swap x and y to make the function work...
It is not gradient that swaps dimensions, it's everything else...
MATLAB indexes arrays as (row,column), and array sizes are given in the same order, as [height,width].
However, whenever the documentation to any function mentions x and y, the x is always horizontal and y vertical. So in a way MATLAB indexes as (y,x).
The right way to fix your code is:
x = 1:30; nx = length(x);
y = 1:62; ny = length(y);
z = 1:23; nz = length(z);
F = rand(ny,nx,nz); % <<< Note the order here!
[FX,FY,FZ] = gradient(F,x,y,z);
Personal opinion: This is terribly confusing, I have seen lots of people making mistakes because of this, and have made quite a few mistakes myself as well. But they are very consistent with this in the MATLAB documentation, using (i,j) or (x,y) depending on the required order -- with the exception of ndgrid, where the documentation uses x1,x2,x3,... but should really have used a different letter.
Related
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
scatter3(X,Y,Z)
Error using scatter3 (line 64)
X, Y and Z must be vectors of the same length.
Matlab R2018b windows x64
As shown in the documentation, X, Y, Z must be vectors. (When you enter an article on mathworks from Googling, say, "matlab scatter3", you will first see the syntax for the function. Blue text means hyperlink. All the inputs are linked to the bottom of the page where their exact typing is defined.)
The reason is (probably) as follows.
As stated in the documentation, scatter3 puts circles (or other symbols of your choice if you modify the graphic object) on 3D coordinates of your choice. The coordinates are the ith element of X, Y, Z respectively. For example, the x-coordinate of the 10th point you wish to plot in 3D is X(10).
Thus it is not natural to input matrices into scatter3. If you know X(i), Y(i), Z(i) are indeed the coordinates you want to plot for all i, even though your X, Y, Z are not vectors for some reason, you need to reshape X, Y, Z.
In order to reshape, you can simply do scatter3(X(:), Y(:), Z(:)) which tells Matlab to read your arrays as a vectors. (You should look up in what order this is done. But it is in the intuitive way.) Or you can use reshape. Chances are: reshape is faster for large data set. But ofc (:) is more convenient.
The following should work:
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
X = X(:);
Y = Y(:);
Z = Z(:);
scatter3(X,Y,Z)
scatter3 needs vectors, not matrices as far as I can see here
this is my result:
If you want to use meshgrid without reshaping the matrices you have to use plot3 and the 'o' symbol. So you can get a similar result with:
plot3(X,Y,Z,'o')
EDIT:
A question that arose in association with this post was, which of the following methods is more efficient in terms of computation speed: The function reshape(X,[],1), suggested by me, or the simpler colon version X(:), suggested by #Argyll.
After timing the reshape function versus the : method, I have to admit that the latter is more efficient.
I added my results and the code I used to time both functions:
sizes = linspace(100,10000,100);
time_reshape = [];
time_col = [];
for i=1:length(sizes)
X = rand(sizes(i)); % Create random squared matrix
r = #() ResFcn(X);
c = #() ColFcn(X);
time_reshape = [time_reshape timeit(r)/1000] % Take average of 1000 measurements
time_col = [time_col timeit(c)/1000] % Take average of 1000 measurements
end
figure()
hold on
grid on
plot(sizes(2:end), time_col(2:end))
plot(sizes(2:end), time_reshape(2:end))
legend("Colon","Reshape","Location","northwest")
title("Comparison: Reshape vs. Colon Method")
xlabel("Length of squared matrix")
ylabel("Average execution time [s]")
hold off
function res = ResFcn(X)
for i = 1:1000 % Repeat 1000 times
res = reshape(X,[],1);
end
end
function res = ColFcn(X)
for i = 1:1000 % Repeat 1000 times
res = X(:);
end
end
I am trying to fit 3D data points (>1000) with the implicit function of a cylinder (5 parameters : a,b,c,d,r) :
-r + sqrt((x-(x+a*(-b+y)+c*(-d+z))/(1+a^2+c^2))^2+(-b+y-(a*(x+a*(-b+y)+c*(-d+z)))/(1+a^2+c^2))^2+(-d+z-(c*(x+a*(-b+y)+c*(-d+z)))/(1+a^2+c^2))^2) == 0
I can't find a good way to implement that with Matlab (my knowledge is till very shallow in Matlab syntax). It would be much easier with a explicit function for sure. I have looked extensively on the net and I haven't found any specific answer.
I have also the parametric function of the cylinder using the same parameters if you know a way to fit the parametric equation directly?
x = v-(c*r*cos(u))/(sqrt(1+c^2))-(a*r*sin(u))/((1+c^2)*sqrt(1+(a^2)/(1+c^2)));
y = b+a*v+(r*sin(u))/(sqrt(1+(a^2)/(1+c^2)));
z = d+c*v+(r*cos(u))/(sqrt(1+c^2))-(a*c*r*sin(u))/((1+c^2)*sqrt(1+(a^2)/(1+c^2)));
Thanks a lot in advance.
You can use cftool with a user define function of the cylinder form you specify above. From the docs,
cftool( x, y, z ) creates a surface fit to x and y inputs and z output. x, y, and z must be numeric, have two or more elements, and have compatible sizes. Sizes are compatible if x, y, and z all have the same number of elements or x and y are vectors, z is a 2D matrix, length(x ) = n, and length(y) = m where [m,n] = size(z). cftool opens Curve Fitting app if necessary.
If you just type cftool it will open an interactive session where you can try some fits (assuming you have the toolbox)...
EDIT: You can use fsolve in this case. Save the cylinder function to a separate file called cylinder, where the code is something like:
function F = cylinder(P, X)
a = P(1);
b = P(2);
c = P(3);
d = P(4);
r = P(5);
x = X(1,:);
y = X(2,:);
z = X(3,:);
% f(x,y,z) - r = 0
F = sqrt( ( x-( (x+a*(-b+y)+c*(-d+z)))/(1+a^2+c^2)).^2 ...
+(-b+y-(a*(x+a*(-b+y)+c*(-d+z)))/(1+a^2+c^2)).^2 ...
+(-d+z-(c*(x+a*(-b+y)+c*(-d+z)))/(1+a^2+c^2)).^2 ) -r;
end
I've assumed you have the correct form of cylinder here. You would call this with you N data points, X in form (3,N),
startparams = [0,0,0,0,1]
coeff=fsolve('cylinder',startparams,[],X)
We were asked to define our own differential operators on MATLAB, and I did it following a series of steps, and then we should use the differential operators to solve a boundary value problem:
-y'' + 2y' - y = x, y(0) = y(1) =0
my code was as follows, it was used to compute this (first and second derivative)
h = 2;
x = 2:h:50;
y = x.^2 ;
n=length(x);
uppershift = 1;
U = diag(ones(n-abs(uppershift),1),uppershift);
lowershift = -1;
L= diag(ones(n-abs(lowershift),1),lowershift);
% the code above creates the upper and lower shift matrix
D = ((U-L))/(2*h); %first differential operator
D2 = (full (gallery('tridiag',n)))/ -(h^2); %second differential operator
d1= D*y.'
d2= ((D2)*y.')
then I changed it to this after posting it here and getting one response that encouraged the usage of Identity Matrix, however I still seem to be getting no where.
h = 2;
n=10;
uppershift = 1;
U = diag(ones(n-abs(uppershift),1),uppershift);
lowershift = -1;
L= diag(ones(n-abs(lowershift),1),lowershift);
D = ((U-L))/(2*h); %first differential operator
D2 = (full (gallery('tridiag',n)))/ -(h^2); %second differential operator
I= eye(n);
eqn=(-D2 + 2*D - I)*y == x
solve(eqn,y)
I am not sure how to proceed with this, like should I define y and x, or what exactly? I am clueless!
Because this is a numerical approximation to the solution of the ODE, you are seeking to find a numerical vector that is representative of the solution to this ODE from time x=0 to x=1. This means that your boundary conditions make it so that the solution is only valid between 0 and 1.
Also this is now the reverse problem. In the previous post we did together, you know what the input vector was, and doing a matrix-vector multiplication produced the output derivative operation on that input vector. Now, you are given the output of the derivative and you are now seeking what the original input was. This now involves solving a linear system of equations.
Essentially, your problem is now this:
YX = F
Y are the coefficients from the matrix derivative operators that you derived, which is a n x n matrix, X would be the solution to the ODE, which is a n x 1 vector and F would be the function you are associating the ODE with, also a n x 1 vector. In our case, that would be x. To find Y, you've pretty much done that already in your code. You simply take each matrix operator (first and second derivative) and you add them together with the proper signs and scales to respect the left-hand side of the ODE. BTW, your first derivative and second derivative matrices are correct. What's left is adding the -y term to the mix, and that is accomplished by -eye(n) as you have found out in your code.
Once you formulate your Y and F, you can use the mldivide or \ operator and solve for X and get the solution to this linear system via:
X = Y \ F;
The above essentially solves the linear system of equations formed by Y and F and will be stored in X.
The first thing you need to do is define a vector of points going from x=0 to x=1. linspace is probably the most suitable where you can specify how many points we want. Let's assume 100 points for now:
x = linspace(0,1,100);
Therefore, h in our case is just 1/100. In general, if you want to solve from the starting point x = a up to the end point x = b, the step size h is defined as h = (b - a)/n where n is the total number of points you want to solve for in the ODE.
Now, we have to include the boundary conditions. This simply means that we know the beginning and ending of the solution of the ODE. This means that y(0) = y(1) = 0. As such, we make sure that the first row of Y has only the first column set to 1 and the last row of Y has only the last column set to 1, and we'll set the output position in F to both be 0. This symbolizes that we already know the solution at these points.
Therefore, your final code to solve is just:
%// Setup
a = 0; b = 1; n = 100;
x = linspace(a,b,n);
h = (b-a)/n;
%// Your code
uppershift = 1;
U = diag(ones(n-abs(uppershift),1),uppershift);
lowershift = -1;
L= diag(ones(n-abs(lowershift),1),lowershift);
D = ((U-L))/(2*h); %first differential operator
D2 = (full (gallery('tridiag',n)))/ -(h^2);
%// New code - Create differential equation matrix
Y = (-D2 + 2*D - eye(n));
%// Set boundary conditions on system
Y(1,:) = 0; Y(1,1) = 1;
Y(end,:) = 0; Y(end,end) = 1;
%// New code - Create F vector and set boundary conditions
F = x.';
F(1) = 0; F(end) = 0;
%// Solve system
X = Y \ F;
X should now contain your numerical approximation to the ODE in steps of h = 1/100 starting from x=0 up to x=1.
Now let's see what this looks like:
figure;
plot(x, X);
title('Solution to ODE');
xlabel('x'); ylabel('y');
You can see that y(0) = y(1) = 0 as per the boundary conditions.
Hope this helps, and good luck!
I was trying to plot the above surface in octave/matlab and ran into the this problem.
My code is as follows:
x = linspace(-sqrt(3),sqrt(3),1000);
y = linspace(-sqrt(2),sqrt(2),1000);
z = sqrt(6-2*x.^2-3*y.^2);
surf(x,y,z)
I got the error:
error: mesh: X, Y, Z arguments must be real.
I understand this was because some (x,y)s would result in negative 6-2*x.^2-3*y.*2, but I don't know how to tackle this because I can't trim either part of x or y. Any one can help? Thanks
It depends what you want to do with the non-real values of z.
One thing you could do is to set all these values to zero or NaN (as per #hbaderts' comment):
z = sqrt(6-2*x.^2-3*y.^2);
z( imag(z)~=0 ) = NaN;
One more thing though: your code might have a problem because z is a length-1000 vector, and you want it to be a 1000x1000 matrix. You should use meshgrid() on x and y to get two-dimensional matrices everywhere:
x = linspace(-sqrt(3),sqrt(3),1000);
y = linspace(-sqrt(2),sqrt(2),1000);
[xx,yy] = meshgrid(x,y);
z = sqrt(6-2*xx.^2-3*yy.^2);
z( imag(z)~=0 ) = NaN;
surf(xx,yy,z,'edgecolor','none')
(thanks #LuisMendo for the 'edgecolor','none' suggestion for better visualization.)
Running the above piece of code on octave gives this plot:
I have an ellipse in 2 dimensions, defined by a positive definite matrix X as follows: a point x is in the ellipse if x'*X*x <= 1. How can I plot this ellipse in matlab? I've done a bit of searching while finding surprisingly little.
Figured out the answer actually: I'd post this as an answer, but it won't let me (new user):
Figured it out after a bit of tinkering. Basically, we express the points on the ellipse border (x'*X*x = 1) as a weighted combination of the eigenvectors of X, which makes some of the math to find the points easier. We can just write (au+bv)'X(au+bv)=1 and work out the relationship between a,b. Matlab code follows (sorry it's messy, just used the same notation that I was using with pen/paper):
function plot_ellipse(X, varargin)
% Plots an ellipse of the form x'*X*x <= 1
% plot vectors of the form a*u + b*v where u,v are eigenvectors of X
[V,D] = eig(X);
u = V(:,1);
v = V(:,2);
l1 = D(1,1);
l2 = D(2,2);
pts = [];
delta = .1;
for alpha = -1/sqrt(l1)-delta:delta:1/sqrt(l1)+delta
beta = sqrt((1 - alpha^2 * l1)/l2);
pts(:,end+1) = alpha*u + beta*v;
end
for alpha = 1/sqrt(l1)+delta:-delta:-1/sqrt(l1)-delta
beta = -sqrt((1 - alpha^2 * l1)/l2);
pts(:,end+1) = alpha*u + beta*v;
end
plot(pts(1,:), pts(2,:), varargin{:})
I stumbled across this post while searching for this topic, and even though it's settled, I thought I might provide another simpler solution, if the matrix is symmetric.
Another way of doing this is to use the Cholesky decomposition of the semi-definite positive matrix E implemented in Matlab as the chol function. It computes an upper triangular matrix R such that X = R' * R. Using this, x'*X*x = (R*x)'*(R*x) = z'*z, if we define z as R*x.
The curve to plot thus becomes such that z'*z=1, and that's a circle. A simple solution is thus z = (cos(t), sin(t)), for 0<=t<=2 pi. You then multiply by the inverse of R to get the ellipse.
This is pretty straightforward to translate into the following code:
function plot_ellipse(E)
% plots an ellipse of the form xEx = 1
R = chol(E);
t = linspace(0, 2*pi, 100); % or any high number to make curve smooth
z = [cos(t); sin(t)];
ellipse = inv(R) * z;
plot(ellipse(1,:), ellipse(2,:))
end
Hope this might help!