I'm trying to plot sphere function below, But I'm getting wrong result
Here is the code I'm using
x1 = [-10:1:10];
x2 = [-10:1:10];
y = zeros(1,21);
for i = 1:21
y(i) = sphere([x1(i) x2(i)]);
end
Y = meshgrid(y);
surf(x1,x2,Y);
colormap hsv;
sphere.m
function [y] = sphere(x)
d = length(x);
sum = 0;
for i = 1:d
sum = sum + x(i)^2;
end
y = sum;
end
For the sake of completness your code is not working because you are only evaluating your function on the pairs (x,x) for some x \in [-10,10] so you don't cover the whole domain. It would work with this:
x1 = [-10:1:10];
x2 = [-10:1:10];
y = zeros(1,21);
for i = 1:21
for j=1:21
Y(i,j) = sphere([x1(i) x2(j)]);
end
end
surf(x1,x2,Y);
colormap hsv;
or way faster (because you should always avoid unnecessary loops for computation time reasons):
x1 = meshgrid([-10:1:10]);
x2 = x1';
Y = x1.^2+x2.^2;
surf(x1,x2,Y)
sphere(10)
It is a MatLab built in function.
Please enjoy responsibly.
If you need to see the source code use: edit sphere or help sphere when your sphere function is not on the path.
Related
I am trying to plot and then to use it with Matlab
in an ODE as coefficient, the function
f : [2,500] -> [0,1],
But I don't know how to write the code for the definition of the function, since it is given on different subintervals.
Below is an example that uses anonymous functions/function handles. It uses each region/condition and evaluates the boundaries numerically and stores them into variables Bounds_1 and Bounds_2. These boundaries are then used to truncate each signal by multiplying each section of the piecewise function by its corresponding condition which is a logical array. It's also good to note that this plot will almost be seen as an impulse since the bounds are really small. Alternatively, you can probably achieve the same results using the built-in piecewise() function but I think this method gives a little more insight. As i increases you'll see a plot that resembles more and more of an impulse. To plot this for multiple values or i this can be run in a for-loop.
clc;
i = 3;
Bounds_1 = [i - (1/i^2),i];
Bounds_2 = [i,i + (1/i^2)];
Bounds = [Bounds_1 Bounds_2];
Min = min(Bounds);
Max = max(Bounds);
f1 = #(x) (i^2.*x - i^3 + 1).*(Bounds_1(1) < x & x <= Bounds_1(2));
f2 = #(x) (-i^2.*x + i^3 + 1).*(Bounds_2(1) < x & x <= Bounds_2(2));
f = #(x) f1(x) + f2(x);
fplot(f);
xlim([Min-2 Max+2]);
ylim([0 1.1]);
Here is another solution. You can specify the steps along the x-axis withxstep. With xlower and xupper you can specify the range of the x-axis:
figure ; hold on;
xlabel('x'); ylabel('f(x)');
for i= 2:500
[f,x] = myfunction(0.5,i);
plot (x,f,'DisplayName',sprintf('%i',i));
end
% legend
function [f,x]=myfunction(xstep,i)
%xstep: specifies steps for the x values
% specify max range x \in = [xlower -> xupper]
xlower = -10;
xupper = 600;
x2 = (i-1/i^2): xstep: i;
f2 = i^2*x2 - i^3 + 1;
x3 = i+xstep:xstep:(1+1/i^2);
f3 = -i^2*x3 + i^3 +1;
x1 = xlower:xstep:(i-1/i^2);
f1 = 0*x1;
x4 = (i+1/i^2):xstep:xupper;
f4 = 0*x4;
f = [f1,f2,f3,f4];
x = [x1,x2,x3,x4];
end
Here is what I get
Besides, I am not exactly sure what you mean with ODE (ordinary differential equation) in f(x). For me it seems like an algebraic equation.
I am trying to make an animation of the 2d wave equation in MATLAB (R2020a). So far I believe that the finite difference method is implemented correctly. However; when I try to plot these values using the "surf" command in matlab it does not work.
This is my script so far:
clear
clc
close all
VL = 2;
tMin = 0;
tMax = 30;
xMin = -10;
xMax = 10;
yMin = -10;
yMax = 10;
Nt = 100;
Nx = 100;
Ny = 100;
t = linspace(tMin,tMax,Nt);
x = linspace(xMin,xMax,Nx);
y = linspace(yMin,yMax,Ny);
DeltaT = t(2) - t(1);
DeltaX = x(2) - x(1);
DeltaY = y(2) - y(1);
CFX = ((VL)*(DeltaT/DeltaX))^2;
CFY = ((VL)*(DeltaT/DeltaY))^2;
u = zeros(Nt,Nx,Ny);
[X,Y] = meshgrid(x,y);
u(1,:,:) = Initial(t(1),X,Y);
u(2,:,:) = Initial(t(1),X,Y) + InitialV(t(1),X,Y);
for i=3:Nt
for j=1:Nx
for k=1:Ny
if(j==1 || j==Nx || k==1 || k==Ny)
u(i,j,k) = 0;
else
u(i,j,k) = 2*u(i-1,j,k) - u(i-2,j,k) + (CFX)*(u(i-1,j+1,k) - 2*u(i-1,j,k) + u(i-1,j-1,k)) + (CFY)*(u(i-1,j,k+1) - 2*u(i-1,j,k) + u(i-1,j,k-1));
end
end
end
end
the functions: Initial and initialV are u(0,x,y) and ut(0,x,y) respectively.
I believe this code works for finding the function values for u however when I try to plot the results as follows:
for i=1:Nt
figure
clf
hold on
surf(X,Y,u(i,:,:))
end
I get an error saying Z must be a matrix... In my opinion this seems strange, slicing a 3d array results in a 2d matrix.
How can I make an animation that shows u as a function of x and y?
Thanks in advance! any help is greatly appreciated
P.S. I am new to this page so if I am neglecting certain guidelines when it comes to sharing code please let me know and I will adjust it.
Another way to remove the singleton dimension of your u array would be to use squeeze() as it doesn't need any information on the remaining size of the array.
for i = 1:Nt
figure
clf
hold on
surf(X, Y, squeeze(u(i, :, :)))
end
To force u(i,:,:) to match the 100 by 100 dimensions of X and Y try using the reshape() function.
for i=1:Nt
figure
clf
hold on
surf(X,Y,reshape(u(i,:,:),[100 100]));
end
I want to plot the field distribution inside a circular structure with radius a.
What I expect to see are circular arrows that from the centre 0 go toward a in the radial direction like this
but I'm obtaining something far from this result. I wrote this
x_np = besselzero(n, p, 1); %toolbox from mathworks.com for the roots
R = 0.1:1:a; PHI = 0:pi/180:2*pi;
for r = 1:size(R,2)
for phi = 1:size(PHI,2)
u_R(r,phi) = -1/2*((besselj(n-1,x_np*R(1,r)/a)-besselj(n+1,x_np*R(1,r)/a))/a)*cos(n*PHI(1,phi));
u_PHI(r,phi) = n*(besselj(n,x_np*R(1,r)/a)/(x_np*R(1,r)))*sin(PHI(1,phi));
end
end
[X,Y] = meshgrid(R);
quiver(X,Y,u_R,u_PHI)
where u_R is supposed to be the radial component and u_PHI the angular component. Supposing the formulas that I'm writing are correct, do you think there is a problem with for cycles? Plus, since R and PHI are not with the same dimension (in this case R is 1x20 and PHI 1X361) I also get the error
The size of X must match the size of U or the number of columns of U.
that I hope to solve it if I figure out which is the problem with the cycles.
This is the plot that I get
The problem has to do with a difference in co-ordinate systems.
quiver expects inputs in a Cartesian co-ordinate system.
The rest of your code seems to be expressed in a polar co-ordinate system.
Here's a snippet that should do what you want. The initial parameters section is filled in with random values because I don't have besselzero or the other details of your problem.
% Define initial parameters
x_np = 3;
a = 1;
n = 1;
% Set up domain (Cartesian)
x = -a:0.1:a;
y = -a:0.1:a;
[X, Y] = meshgrid(x, y);
% Allocate output
U = zeros(size(X));
V = zeros(size(X));
% Loop over each point in domain
for ii = 1:length(x)
for jj = 1:length(y)
% Compute polar representation
r = norm([X(ii,jj), Y(ii,jj)]);
phi = atan2(Y(ii,jj), X(ii,jj));
% Compute polar unit vectors
rhat = [cos(phi); sin(phi)];
phihat = [-sin(phi); cos(phi)];
% Compute output (in polar co-ordinates)
u_R = -1/2*((besselj(n-1, x_np*r/a)-besselj(n+1, x_np*r/a))/a)*cos(n*phi);
u_PHI = n*(besselj(n, x_np*r/a)/(x_np*r))*sin(phi);
% Transform output to Cartesian co-ordinates
U(ii,jj) = u_R*rhat(1) + u_PHI*phihat(1);
V(ii,jj) = u_R*rhat(2) + u_PHI*phihat(2);
end
end
% Generate quiver plot
quiver(X, Y, U, V);
I have a matrix for contact positions and these positions are linear, therefore I can easily plot the contact positions within MATLAB and come out with the x amount of lines. At the moment I am plotting within a 2D graph.
for j= 1:5
for k= 1:20
Yijk(j,:,k)=x*tan_helix+one_array*(k-P)*Pb/P+one_array*(j-(L+1)/2)*Pb;
end
end
x_axis = linspace(0,b*1000, N+1);
figure;
for j=1:zPairs;
hold on
plot(x_axis,Yijk(j,:,k))
hold off
end
The above is only a small section of a large coding so all variables and parameters are stated else where.
Below is the graph this simply creates with a 2D graph:
What I wish to do is plot the correspoding contact to each of these positions, contact only occurs at positions > 0 and therefore will only occur along the lines plotted above. Therefore the plot will need to be in a 3D format and I am assuming that the lines will be plotted initially, then the contact_force and then a fill command as such - but I may be wrong.
What I am aiming to create is something similar to:
If any one has any guidance or tips it will be greatly appreciated as I am getting nowhere.
Please note the contact_force is also a matrix of the same dimensions as the contact positions.
for j = 1:zPairs
Xx = linspace(0,b*1000,N+1);
Yy = Yijk(j,:,1);
n = length(Xx);
Zz = contact_force(j,:,1);
Xp = zeros(2*n,1);
Yp = zeros(2*n,1);
Xp(1:N+1) = Xx;
Xp(N+2:2*(N+1)) = Xx(N+1:-1:1);
Yp(1:N+1) = Yy;
Yp(N+2:2*(N+1)) = Yy(N+1:-1:1);
Zp(1:N+1) = 0;
Zp(N+2:2*(N+1)) = Zz(N+1:-1:1);
figure(12);
hold on
patch(Xp,Yp,Zp,'c');
title('Zone of Contact');
hold off
end
The above code works great, but only creates one graph as it is for (j,:,1). I would like to change this so as that it is for (j,:,k) and k number of graphs are created. How would I set up this for loop ?
I wrote a little MATLAB code to test it out. This program creates a polygon on top of a 2D line. fill3 or patch functions are what you are looking for.
a = 2;
b = 1;
X = 0:10;
Y = a*X + b;
n = length(X);
Z = rand(n,1)*2+1;
Xp = zeros(2*n,1);
Yp = zeros(2*n,1);
Xp(1:n) = X;
Xp(n+1:2*n) = X(n:-1:1);
Yp(1:n) = Y;
Yp(n+1:2*n) = Y(n:-1:1);
Zp(1:n) = 0;
Zp(n+1:2*n) = Z(n:-1:1);
fill3(Xp,Yp,Zp,'c');
Hi I have a set of data A with each element corresponding to an x and y combination. When I plot this dat using mesh I get a graph with many spikes on it. This is not unnexpected but I would like a way to smooth these out to get a smooth surface.
I've tried to use the smooth3 command but cannot figure out how to make the suitable input.
Any help would be appreciated. Thanks
This is how my data is generated.
function v = f(x,y) % Not actual function
return x*rand()+y*rand()
end
x = 0.05:0.01:0.95;
y = 0.05:0.01:0.95;
o = zeros(length(x),length(y));
A = zeros(length(x), length(y));
for k = 1:5
for i = 1:length(x)
for j = 1:length(y)
o(i,j) = f([x(i), y(j)]);
end
end
A= A+o;
end
A = A/5;
This is what produces the plot.
[X,Y] = meshgrid(x);
mesh(A)
my be you can try a convolution of your variable A with a filter(the following is an example of a Gaussian filter).
C = conv2(A,fspecial('gaussian', hsize, sigma));
check conv2 and fspecial in matlab help