Plotting the Lagrange interpolated curve on top of the equidistant points - matlab

I have made a simple code for Lagrange interpolation of vectors of data x and y and , but I need some help with plotting and displaying errors.
I wish to plot the equidistant points together with the Lagrange Interpolated curve in the same plot, and display the error of the approximation. Plotting the points is trivial, but I struggle with plotting the interpolated polynomial curve on top of the (x,y) plot.
clear
clc
x = -1:0.25:1;
y = 1./(1+25.*x.^2);
N = 1:length(y);
M = zeros(length(y),length(x));
for n = 1:length(x)
for i = 1:length(y)
l = 1;
index = find(N ~= i);
for jj = 1:length(index)
l = l.*(x(n)-y(index(jj)))./(y(i)-y(index(jj)));
end
M(i,n) = l;
end
end
plot(x,y)
All help is appreciated

Related

Plot quiver polar coordinates

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);

Plotting circles in a Hadamard matrix pattern

I want to plot circles in Hadamard matrix pattern of order 8,16, and 32. So far, I have a code for plotting 2D arrays of circles.
%Plotting an N by N arrays of circles
clc; clear;
n_circles = 8; % Define the number of circles to be plotted
R = 40; % Define the radius of the basic circle
Len=1024;
M=zeros(Len); % Create the hole mask
% Get the indices of the points inside the basic circle
M0 = zeros(2*R+1); % Initialize the basic mask
I = 1:(2*R+1); % Define the x and y coordinates of the basic mask
x = (I - R)-1;
y = (R - I)+1;
[X,Y] = meshgrid(x,y); % Create the mask
A = (X.^2 + Y.^2 <= R^2);
[xx,yy]=ind2sub(size(M0),find(A == true));
%plot
for ii=1:n_circles
for jj=1:n_circles
MidX=Len/2+(ii-n_circles/2-0.5)*(2*R);
MidY=Len/2+(jj-n_circles/2-0.5)*(2*R);
% [MidX MidY]
M(sub2ind(size(M),MidX+xx-R-1,MidY+yy-R-1))=1;
end
end
figure(1)
imshow(M)
I searched on how to plot a Hadamard matrix, and from the Mathworks documentation, the hadamard matrix function
H = hadamard(n)
returns the Hadamard matrix of order n. How do I incorporate this in my original code so that the final result will generate an image of circles plotted in a Hadamard pattern, where the value of 1 indicates a circle while -1 is null (absence of circle)?
Thanks,
add in th begining
H = hadamard(n_circles);
and inside the loops change to:
M(sub2ind(size(M),MidX+xx-R-1,MidY+yy-R-1))=H(ii,jj);

Two plots of same wave in MatLab, but plot created after transforming to polar coordinates is distorded?

I have created some MatLab code that plots a plane wave using two different expressions that give the same plane wave. The first expression is in Cartesian coordinates and works fine. However, the second expression is in polar coordinates and when I calculate the plane wave in this case, the plot is distorted. Both plots should look the same. So what am I doing wrong in transforming to/from polar coordinates?
function Plot_Plane_wave()
clc
clear all
close all
%% Step 0. Input paramaters and derived parameters.
alpha = 0*pi/4; % angle of incidence
k = 1; % wavenumber
wavelength = 2*pi/k; % wavelength
%% Step 1. Define various equivalent versions of the incident wave.
f_u_inc_1 = #(alpha,x,y) exp(1i*k*(x*cos(alpha)+y*sin(alpha)));
f_u_inc_2 = #(alpha,r,theta) exp(1i*k*r*cos(theta-alpha));
%% Step 2. Evaluate the incident wave on a grid.
% Grid for field
gridMax = 10;
gridN = 2^3;
g1 = linspace(-gridMax, gridMax, gridN);
g2 = g1;
[x,y] = meshgrid(g1, g2);
[theta,r] = cart2pol(x,y);
u_inc_1 = f_u_inc_1(alpha,x,y);
u_inc_2 = 0*x;
for ir=1:gridN
rVal = r(ir);
for itheta=1:gridN
thetaVal = theta(itheta);
u_inc_2(ir,itheta) = f_u_inc_2(alpha,rVal,thetaVal);
end
end
%% Step 3. Plot the incident wave.
figure(1);
subplot(2,2,1)
imagesc(g1(1,:), g1(1,:), real(u_inc_1));
hGCA = gca; set(hGCA, 'YDir', 'normal');
subplot(2,2,2)
imagesc(g1(1,:), g1(1,:), real(u_inc_2));
hGCA = gca; set(hGCA, 'YDir', 'normal');
end
Your mistake is that your loop is only going through the first gridN values of r and theta. Instead you want to step through the indices of ix and iy and pull out the rVal and thetaVal of the matrices r and theta.
You can change your loop to
for ix=1:gridN
for iy=1:gridN
rVal = r(ix,iy); % Was equivalent to r(ix) outside inner loop
thetaVal = theta(ix,iy); % Was equivalent to theta(iy)
u_inc_2(ix,iy) = f_u_inc_2(alpha,rVal,thetaVal);
end
end
which gives the expected graphs.
Alternatively you can simplify your code by feeding matrices in to your inline functions. To do this you would have to use an elementwise product .* instead of a matrix multiplication * in f_u_inc_2:
alpha = 0*pi/4;
k = 1;
wavelength = 2*pi/k;
f_1 = #(alpha,x,y) exp(1i*k*(x*cos(alpha)+y*sin(alpha)));
f_2 = #(alpha,r,theta) exp(1i*k*r.*cos(theta-alpha));
% Change v
f_old = #(alpha,r,theta) exp(1i*k*r *cos(theta-alpha));
gridMax = 10;
gridN = 2^3;
[x,y] = meshgrid(linspace(-gridMax, gridMax, gridN));
[theta,r] = cart2pol(x,y);
subplot(1,3,1)
contourf(x,y,real(f_1(alpha,x,y)));
title 'Cartesian'
subplot(1,3,2)
contourf(x,y,real(f_2(alpha,r,theta)));
title 'Polar'
subplot(1,3,3)
contourf(x,y,real(f_old(alpha,r,theta)));
title 'Wrong'

Plotting Ellipse for complex values in matlab

I am trying to plot the elliptical trajectory of a particle, but my matlab code runs and gives me warning that I m trying to plot imaginary values. How can I remove this error?
My Matlab code is as follows:
% plot of trajectory of the particle in flexural gravity wave
U =5;
t=1;
y1=0;
h=50;
k=2*pi/100;
w=pi;
X= (-80*pi:pi:80*pi);
Y= (-80*pi:pi:80*pi);
H=1;
A= (H/2)*cosh(k*(h+y1))/sinh(k*h);
B= (H/2)*sinh(k*(h+y1))/sinh(k*h);
Y = B.* ((1-((X-U*t)./A).^2).^(1/2));
plot(X,Y);
xlabel('X');
ylabel('Y');
The warning matlab shows is:
Warning: Imaginary parts of complex X and/or Y arguments ignored
Please help me out with this.
If you want to plot imaginary number only,
Please change the code, plot(X,Y); as plot(X,imag(Y)).
In case of real value, plot(X,real(Y)).
If you are interested in magnitude of complex number, plot(X,abs(Y)).
I got the answer to my question.
I can plot it by using general coordinates of the ellipse, ie, using x=acos(t) and y=asin(t). and that really worked.
% plot of trajectory of the particle in flexural gravity wave
U = 5;
t = 1;
y1 = 0;
h = 50;
k = 2*pi/100;
w = pi;
x0 = U*t;
y0 = 0;
H = 1;
A = (H/2)*cosh(k*(h+y1))/sinh(k*h);
B = (H/2)*sinh(k*(h+y1))/sinh(k*h);
z = -2*pi:0.01:2*pi;
X = x0 + A*cos(z);
Y = y0 + B*sin(z);
plot(X,Y);
xlabel('X');
ylabel('Y');

Matlab irregular shape surf-like plot

I intend to use Matlab to plot the probability distribution from stochastic process on its state space. The state space can be represented by the lower triangle of a 150x150 matrix. Please see the figure (a surf plot without mesh) for a probability distribution at a certain time point.
As we can see, there is a high degree of symmetry in the graph, but because it is plotted as a square matrix, it looks kind of weird. It we could transform the rectangle the plot would look perfect. My question is, how can I use Matlab to plot/transform the lower triangle portion as/to an equal-lateral triangle?
This function should do the job for you. If not, please let me know.
function matrix_lower_tri_to_surf(A)
%Displays lower triangle portion of matrix as an equilateral triangle
%Martin Stålberg, Uppsala University, 2013-07-12
%mast4461 at gmail
siz = size(A);
N = siz(1);
if ~(ndims(A)==2) || ~(N == siz(2))
error('Matrix must be square');
end
zeds = #(N) zeros(N*(N+1)/2,1); %for initializing coordinate vectors
x = zeds(N); %x coordinates
y = zeds(N); %y coordinates
z = zeds(N); %z coordinates, will remain zero
r = zeds(N); %row indices
c = zeds(N); %column indices
l = 0; %base index
xt = 1:N; %temporary x coordinates
yt = 1; %temporary y coordinates
for k = N:-1:1
ind = (1:k)+l; %coordinate indices
l = l+k; %update base index
x(ind) = xt; %save temporary x coordinates
%next temporary x coordinates are the k-1 middle pairwise averages
%calculated by linear interpolation through convolution
xt = conv(xt,[.5,.5]);
xt = xt(2:end-1);
y(ind) = yt; %save temporary y coordinates
yt = yt+1; %update temporary y coordinates
r(ind) = N-k+1; %save row indices
c(ind) = 1:k; % save column indices
end
v = A(sub2ind(size(A),r,c)); %extract values from matrix A
tri = delaunay(x,y); %create triangular mesh
h = trisurf(tri,x,y,z,v,'edgecolor','none','facecolor','interp'); %plot surface
axis vis3d; view(2); %adjust axes projection and proportions
daspect([sqrt(3)*.5,1,1]); %adjust aspect ratio to display equilateral triangle
end %end of function