Matlab irregular shape surf-like plot - matlab

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

Related

Would like to generate surface of revolution from bezier curve

I would like to generate surface of revolution from bezier curve. I have made bezier curve in MATLAB but beyond this point I am stuck and do not know how to proceed. Please help.
Below is the code that I have made.
clc
clear
close all
% Name : Savla Jinesh Shantilal
% Bits ID : 2021HT30609
%% Define inout parameters
B = [1,1; 2,3; 4,3; 3,1]; % Creating matrix for polygon vertices
[r,s] = size(B); % getting size of matrix in terms of rows and columns
n = r-1; % n+1 represents number of vertices of the polygon
np = 20; % represents number of equi-distance points on the bezier curve
t = linspace(0,1,np);
%% Plot polygon
for k = 1:n
plot([B(k,1),B(k+1,1)], [B(k,2),B(k+1,2)], 'r', 'LineWidth', 2)
hold on
grid on
end
%% Generate the points on the bezier curve
for j = 1:np
P = [0,0];
for i = 0:n
M(i+1) = (factorial(n)/(factorial(i)*factorial(n-i)))*((t(j))^i)*((1-t(j))^(n-i));
P = P + B(i+1,:)*M(i+1);
end
Q(j,:) = P;
end
%% Plot the bezier curve from the obtained points
for l = 1:np-1
plot([Q(l,1),Q(l+1,1)],[Q(l,2),Q(l+1,2)], '-- b', 'LineWidth', 2);
hold on
end
Usually one can use the built-in cylinder function for monotonically increasing x-values. Here, the bezier curve has non monotonic values from max(x) so we break it to two parts to parameterize it, and then add an angle rotation.
% first define the x and y coordinate from your Q info:
xx = Q(:,1);
yy = Q(:,2);
N = 1e2;
[~, id] = max(xx); % the position where we split
t = linspace(xx(1),xx(id),N);
% Parameterize the function:
t = linspace(0,2*(xx(id)-xx(1)),N);
x = zeros(1, N);
L = t <= ( xx(id)-xx(1) ); % the "Left" side of the curve
x(L) = t(L)+xx(1);
x(~L) = flip(x(L));
%define the r value
r = x;
r(L) = interp1(xx(1:id) ,yy(1:id) , x(L) ); % Left side
r(~L) = interp1(xx(id:end),yy(id:end), x(~L)); % right side (not left)
% define your x values
x = repmat(x', [1 N]);
% define the theta that will perform the rotation
theta = linspace(0,2*pi, N);
% initialize values for y and z
y = zeros(N);
z = zeros(N);
% calculate the y and z values
for i=1:N
y(i,:) = r(i) *cos(theta);
z(i,:) = r(i) *sin(theta);
end
%plot the surface of revolution and the original curve
s = surf(x,y,z);
alpha 0.4
hold on
plot(xx,yy,'k','LineWidth',3)

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

How to interpolate using in polar coordinate

I have polar coordinates, radius 0.05 <= r <= 1 and 0 ≤ θ ≤ 2π. The radius r is 50 values between 0.05 to 1, and polar angle θ is 24 values between 0 to 2π.
How do I interpolate r = 0.075 and theta = pi/8?
I dunno what you have tried, but interp2 works just as well on polar data as it does on Cartesian. Here is some evidence:
% Coordinates
r = linspace(0.05, 1, 50);
t = linspace(0, 2*pi, 24);
% Some synthetic data
z = sort(rand(50, 24));
% Values of interest
ri = 0.075;
ti = pi/8;
% Manually interpolate
rp = find(ri <= r, 1, 'first');
rm = find(ri >= r, 1, 'last');
tp = find(ti <= t, 1, 'first');
tm = find(ti >= t, 1, 'last');
drdt = (r(rp) - r(rm)) * (t(tp) - t(tm));
dr = [r(rp)-ri ri-r(rm)];
dt = [t(tp)-ti ti-t(tm)];
fZ = [z(rm, tm) z(rm, tp)
z(rp, tm) z(rp, tp)];
ZI_manual = (dr * fZ * dt.') / drdt
% Interpolate with MATLAB
ZI_MATLAB = interp2(r, t, z', ri, ti, 'linear')
Result:
ZI_manual =
2.737907208525297e-002
ZI_MATLAB =
2.737907208525298e-002
Based on comments you have the following information
%the test point
ri=0.53224;
ti = pi/8;
%formula fo generation of Z
g=9.81
z0=#(r)0.01*(g^2)*((2*pi)^-4)*(r.^-5).*exp(-1.25*(r/0.3).^-4);
D=#(t)(2/pi)*cos(t).^2;
z2=#(r,t)z0(r).*D(t) ;
%range of vlaues of r and theta
r=[0.05,0.071175,0.10132,0.14422,0.2053, 0.29225,0.41602,0.5922,0.84299,1.2];
t=[0,0.62832,1.2566,1.885, 2.5133,3.1416,3.7699,4.3982,5.0265,5.6549,6.2832];
and you want interplation of the test point.
When you sample some data to use them for interpolation you should consider how to sample data according to your requirements.
So when you are sampling a regular grid of polar coordinates ,those coordinates when converted to rectangular will form a circular shape that
most of the points are concentrated in the center of the cricle and when we move from the center to outer regions distance between the points increased.
%regular grid generated for r and t
[THETA R] = meshgrid(t ,r);
% Z for polar grid
Z=z2(R,THETA);
%convert coordinate from polar to cartesian(rectangular):
[X, Y] = pol2cart (THETA, R);
%plot points
plot(X, Y, 'k.');
axis equal
So when you use those point for interpolation the accuracy of the interpolation is greater in the center and lower in the outer regions where the distance between points increased.
In the other word with this sampling method you place more importance on the center region related to outer ones.
To increase accuracy density of grid points (r and theta) should be increased so if length of r and theta is 11 you can create r and theta with size 20 to increase accuracy.
In the other hand if you create a regular grid in rectangular coordinates an equal importance is given to each region . So accuracy of the interpolation will be the same in all regions.
For it first you create a regular grid in the polar coordinates then convert the grid to rectangular coordinates so you can calculate the extents (min max) of the sampling points in the rectangular coordinates. Based on this extents you can create a regular grid in the rectangular coordinates
Regular grid of rectangular coordinates then converted to polar coordinated to get z for grid points using z2 formula.
%get the extent of points
extentX = [min(X(:)) max(X(:))];
extentY = [min(Y(:)) max(Y(:))];
%sample 100 points(or more or less) inside a region specified be the extents
X_samples = linspace(extentX(1),extentX(2),100);
Y_samples = linspace(extentY(1),extentY(2),100);
%create regular grid in rectangular coordinates
[XX YY] = meshgrid(X_samples, Y_samples);
[TT RR] = cart2pol(XX,YY);
Z_rect = z2(RR,TT);
For interpolation of a test point say [ri ti] first it converted to rectangular then using XX ,YY value of z is interpolated
[xi yi] = pol2cart (ti, ri);
z=interp2(XX,YY,Z_rect,xi,yi);
If you have no choice to change how you sample the data and only have a grid of polar points as discussed with #RodyOldenhuis you can do the following:
Interpolate polar coordinates with interp2 (interpolation for gridded data)
this approach is straightforward but has the shortcoming that r and theta are not of the same scale and this may affect the accuracy of the interpolation.
z = interp2(THETA, R, Z, ti, ri)
convert polar coordinates to rectangular and then apply an interpolation method that is for scattered data.
this approach requires more computations but result of it is more reliable.
MATLAB has griddata function that given scattered points first generates a triangulation of points and then creates a regular grid on top of the triangles and interpolates values of grid points.
So if you want to interpolate value of point [ri ti] you should then apply a second interpolation to get value of the point from the interpolated grid.
With the help of some information from spatialanalysisonline and Wikipedia linear interpolation based on triangulation calculated this way (tested in Octave. In newer versions of MATLAB use of triangulation and pointLocation recommended instead of delaunay and tsearch ):
ri=0.53224;
ti = pi/8;
[THETA R] = meshgrid(t ,r);
[X, Y] = pol2cart (THETA, R);
[xi yi] = pol2cart (ti, ri);
%generate triangulation
tri = delaunay (X, Y);
%find the triangle that contains the test point
idx = tsearch (X, Y, tri, xi, yi);
pts= tri(idx,:);
%create a matrix that repesents equation of a plane (triangle) given its 3 points
m=[X(pts);Y(pts);Z(pts);ones(1,3)].';
%calculate z based on det(m)=0;
z= (-xi*det(m(:,2:end)) + yi*det([m(:,1) m(:,3:end)]) + det(m(:,1:end-1)))/det([m(:,1:2) m(:,end)]);
More refinement:
Since it is known that the search point is surrounded by 4 points we can use only those point for triangulation. these points form a trapezoid. Each diagonal of trapezoid forms two triangles so using vertices of the trapezoid we can form 4 triangles, also a point inside a trapezoid can lie in at least 2 triangles.
the previous method based on triangulation only uses information from one triangle but here z of the test point can be interpolated two times from data of two triangles and the calculated z values can be averaged to get a better approximation.
%find 4 points surrounding the test point
ft= find(t<=ti,1,'last');
fr= find(cos(abs(diff(t(ft+(0:1))))/2) .* r < ri,1,'last');
[T4 R4] = meshgrid(t(ft+(0:1)), r(fr+(0:1)));
[X4, Y4] = pol2cart (T4, R4);
Z4 = Z(fr+(0:1),ft+(0:1));
%form 4 triangles
tri2= nchoosek(1:4,3);
%empty vector of z values that will be interpolated from 4 triangles
zv = NaN(4,1);
for h = 1:4
pts = tri2(h,:);
% test if the point lies in the triangle
if ~isnan(tsearch(X4(:),Y4(:),pts,xi,yi))
m=[X4(pts) ;Y4(pts) ;Z4(pts); [1 1 1]].';
zv(h)= (-xi*det(m(:,2:end)) + yi*det([m(:,1) m(:,3:end)]) + det(m(:,1:end-1)))/det([m(:,1:2) m(:,end)]);
end
end
z= mean(zv(~isnan(zv)))
Result:
True z:
(0.0069246)
Linear Interpolation of (Gridded) Polar Coordinates :
(0.0085741)
Linear Interpolation with Triangulation of Rectangular Coordinates:
(0.0073774 or 0.0060992) based on triangulation
Linear Interpolation with Triangulation of Rectangular Coordinates(average):
(0.0067383)
Conclusion:
Result of interpolation related to structure of original data and the sampling method. If the sampling method matches pattern of original data result of interpolation is more accurate, so in cases that grid points of polar coordinates follow pattern of data result of interpolation of regular polar coordinate can be more reliable. But if regular polar coordinates do not match the structure of data or structure of data is such as an irregular terrain, method of interpolation based on triangulation can better represent the data.
please check this example, i used two for loops, inside for loop i used condition statement, if u comment this condition statement and run the program, u'll get correct answer, after u uncomment this condition statement and run the program, u'll get wrong answer. please check it.
% Coordinates
r = linspace(0.05, 1, 10);
t = linspace(0, 2*pi, 8);
% Some synthetic data
%z = sort(rand(50, 24));
z=zeros();
for i=1:10
for j=1:8
if r(i)<0.5||r(i)>1
z(i,j)=0;
else
z(i,j) = r(i).^3'*cos(t(j)/2);
end
end
end
% Values of interest
ri = 0.55;
ti = pi/8;
% Manually interpolate
rp = find(ri <= r, 1, 'first');
rm = find(ri >= r, 1, 'last');
tp = find(ti <= t, 1, 'first');
tm = find(ti >= t, 1, 'last');
drdt = (r(rp) - r(rm)) * (t(tp) - t(tm));
dr = [r(rp)-ri ri-r(rm)];
dt = [t(tp)-ti ti-t(tm)];
fZ = [z(rm, tm) z(rm, tp)
z(rp, tm) z(rp, tp)];
ZI_manual = (dr * fZ * dt.') / drdt
% Interpolate with MATLAB
ZI_MATLAB = interp2(r, t, z', ri, ti, 'linear')
Result:
z1 =
0.1632
ZI_manual =
0.1543
ZI_MATLAB =
0.1582

How to find the area of an arbitrary shape contained within a circle using MATLAB

I have an arbitrary shape, of which the exterior boundary has been traced in MATLAB using bwboundaries. Using regionprops, I can calculate the total area enclosed by this shape.
However, I want to know the area for only the parts of the shape that fall within a circle of known radius R centered at coordinates [x1, y1]. What is the best way to accomplish this?
There are a few ways to approach this. One way you could alter the mask before performing bwboundaries (or regionprops) so that it only includes pixels which are within the given circle.
This example assumes that you already have a logical matrix M that you pass to bwboundaries.
function [A, boundaries] = traceWithinCircle(M, x1, y1, R);
%// Get pixel centers
[x,y] = meshgrid(1:size(M, 1), 1:size(M, 2));
%// Compute their distance from x1, y1
distances = sqrt(sum(bsxfun(#minus, [x(:), y(:)], [x1, y1]).^2, 2));
%// Determine which are inside of the circle with radius R
isInside = distances <= R;
%// Set the values outside of this circle in M to zero
%// This will ensure that they are not detected in bwboundaries
M(~isInside) = 0;
%// Now perform bwboundaries on things that are
%// inside the circle AND were 1 in M
boundaries = bwboundaries(M);
%// You can, however, get the area by simply counting the number of 1s in M
A = sum(M(:));
%// Of if you really want to use regionprops on M
%// props = regionprops(M);
%// otherArea = sum([props.Area]);
end
And as an example
%// Load some example data
data = load('mri');
M = data.D(:,:,12) > 60;
%// Trace the boundaries using the method described above
B = traceWithinCircle(M, 70, 90, 50);
%// Display the results
figure;
hax = axes();
him = imagesc(M, 'Parent', hax);
hold(hax, 'on');
colormap gray
axis(hax, 'image');
%// Plot the reference circle
t = linspace(0, 2*pi, 100);
plot(x1 + cos(t)*R, y1 + sin(t)*R);
%// Plot the segmented boundaries
B = bwboundaries(M);
for k = 1:numel(B)
plot(B{k}(:,2), B{k}(:,1), 'r');
end

examples to convert image to polar coordinates do it explicitly - want a slick matrix method

I am trying to convert an image from cartesian to polar coordinates.
I know how to do it explicitly using for loops, but I am looking for something more compact.
I want to do something like:
[x y] = size(CartImage);
minr = floor(min(x,y)/2);
r = linspace(0,minr,minr);
phi = linspace(0,2*pi,minr);
[r, phi] = ndgrid(r,phi);
PolarImage = CartImage(floor(r.*cos(phi)) + minr, floor(r.sin(phi)) + minr);
But this obviously doesn't work.
Basically I want to be able to index the CartImage on a grid.
The polar image would then be defined on the grid.
given a matrix M (just a 2d Gaussian for this example), and a known origin point (X0,Y0) from which the polar transform takes place, we expect that iso-intensity circles will transform to iso-intensity lines:
M=fspecial('gaussian',256,32); % generate fake image
X0=size(M,1)/2; Y0=size(M,2)/2;
[Y X z]=find(M);
X=X-X0; Y=Y-Y0;
theta = atan2(Y,X);
rho = sqrt(X.^2+Y.^2);
% Determine the minimum and the maximum x and y values:
rmin = min(rho); tmin = min(theta);
rmax = max(rho); tmax = max(theta);
% Define the resolution of the grid:
rres=128; % # of grid points for R coordinate. (change to needed binning)
tres=128; % # of grid points for theta coordinate (change to needed binning)
F = TriScatteredInterp(rho,theta,z,'natural');
%Evaluate the interpolant at the locations (rhoi, thetai).
%The corresponding value at these locations is Zinterp:
[rhoi,thetai] = meshgrid(linspace(rmin,rmax,rres),linspace(tmin,tmax,tres));
Zinterp = F(rhoi,thetai);
subplot(1,2,1); imagesc(M) ; axis square
subplot(1,2,2); imagesc(Zinterp) ; axis square
getting the wrong (X0,Y0) will show up as deformations in the transform, so be careful and check that.
I notice that the answer from bla is from polar to cartesian coordinates.
However the question is in the opposite direction.
I=imread('output.png'); %read image
I1=flipud(I);
A=imresize(I1,[1024 1024]);
A1=double(A(:,:,1));
A2=double(A(:,:,2));
A3=double(A(:,:,3)); %rgb3 channel to double
[m n]=size(A1);
[t r]=meshgrid(linspace(-pi,pi,n),1:m); %Original coordinate
M=2*m;
N=2*n;
[NN MM]=meshgrid((1:N)-n-0.5,(1:M)-m-0.5);
T=atan2(NN,MM);
R=sqrt(MM.^2+NN.^2);
B1=interp2(t,r,A1,T,R,'linear',0);
B2=interp2(t,r,A2,T,R,'linear',0);
B3=interp2(t,r,A3,T,R,'linear',0); %rgb3 channel Interpolation
B=uint8(cat(3,B1,B2,B3));
subplot(211),imshow(I); %draw the Original Picture
subplot(212),imshow(B); %draw the result