Insert random noise in a V slope DEM - matlab

With the following code I am generating a V plane with 2 different slopes, 10° and 20° respectively.
% /*
% Assumptions
% */
% resolution [m]
res = 1;
% inclination [deg]
i1 = 10; i2 = 20;
% /*
% DEM -> V shape
% */
% pre-allocate output
testDEM = zeros(513);
% required elevation step [m]
hstep = res*tan(i1*(pi/180));
% elevation start right [m]
k = 513*(2/3)*tan(i1*(pi/180));
% coordinates
q = length(1:513*(2/3));
% initialize
nStep = 0;
for jj = 1:q
testDEM(:,jj) = k-nStep;
nStep = nStep + hstep;
end
% change elevation step
step = res*tan(i2*(pi/180));
% update nStep
nStep = step;
% elevation start left [m]
start = testDEM(end,q);
for jj = q+1:513
testDEM(:,jj) = start + nStep;
nStep = nStep + step;
end
testDEM = testDEM(1:507,1:507);
%//Plot test DEM
f_tSlope = figure();
set(gca,'PlotBoxAspectRatio',[1 1 1]);
surf(testDEM, 'EdgeColor', 'none')
colormap jet;
hb = colorbar('location','eastoutside');
hb.Label.String = '[m]';
hb.Label.Rotation = 0;
hb.Label.HorizontalAlignment = 'Left';
With the following I'm adding noise in every location
sigma = 1;
testDEM = testDEM + sigma*randn(size(testDEM));
But what I'd like instead is to add random noise in random location, not everywhere. How can I do it?
Thanks in advance

How about this:
N_locations = 100; % no. of locations to add random noise
% randomize 'N_locations' linear indecies in 'testDEM':
noise_location = randi(numel(testDEM),N_locations,1);
% add the noise:
testDEM(noise_location) = testDEM(noise_location)+sigma*randn(N_locations,1);
This will randomize N_locations random locations on the map, and apply different random noise to each of them.
If you prefer to add the same noise to all random locations, just write sigma*randn, without the parenthesis after it.
For small N_locations this should suffice. However, if you want to make sure you don't pick the same location twice, or N_locations is large, you can set noise_location like this:
noise_location = randperm(numel(testDEM),N_locations);
so you'll have only non-repeating values of indices in testDEM.

This code adds noise with 0.5 probability
testDEM = testDEM + sigma*randn(size(testDEM)) .* (rand(size(testDEM)) > 0.5);

Related

How can I rotate a plot in MATLAB?

I want to rotate the plot scatterplot(rxSig) (shown below) 8 degrees, for example.
(the group of the red dots in the photo)
it's not looks like a regular plot and I didn't found a relevant information for that.
Expected Result: (with rotation)
Plot without rotation:
R = 1000.0;
freq = 28*1e9;
T = 20.0;
lwd = 0.5;
F = fogpl(R,freq,T,lwd);
P = 101300.0;
W = 7.5;
G = gaspl(R,freq,T,P,W);
RR=[0.75,1.75,2.5,3];
for irr=1:length(RR)
R = rainpl(10000,freq,RR(irr));
L=R+F+G;
end
M = 64; % Modulation order
k = log2(M); % Bits per symbol
EbNoVec = (0:25)'; % Eb/No values (dB)
numSymPerFrame = 1000;
for n = 1:length(EbNoVec)
% Convert Eb/No to SNR
snrdB = EbNoVec(n) + 10*log10(k)-L(1);
% Reset the error and bit counters
numErrs = 0;
numBits = 0;
while numErrs < 200 && numBits < 1e8
% Generate binary data and convert to symbols
dataIn = randi([0 1],numSymPerFrame,k);
dataSym = bi2de(dataIn);
% QAM modulate using 'Gray' symbol mapping
txSig = qammod(dataSym,M);
% Pass through AWGN channel
rxSig = awgn(txSig,snrdB,'measured');
% Demodulate the noisy signal
rxSym = qamdemod(rxSig,M);
% Convert received symbols to bits
dataOut = de2bi(rxSym,k);
% Calculate the number of bit errors
nErrors = biterr(dataIn,dataOut);
% Increment the error and bit counters
numErrs = numErrs + nErrors;
numBits = numBits + numSymPerFrame*k;
end
% Estimate the BER
berEst(n) = numErrs/numBits;
end
berTheory = berawgn(EbNoVec,'qam',M);
semilogy(EbNoVec,berEst,'*')
hold on
semilogy(EbNoVec,berTheory)
grid
legend('Estimated BER with our attenuation function','Theoretical Matlab BER')
xlabel('Eb/No (dB)')
ylabel('Bit Error Rate')
scatterplot(rxSig)
I combined both my suggestions to create the following code.
% Extract data points from current figure
h = findobj(gca,'Type','line');
x_org=get(h,'Xdata');
y_org=get(h,'Ydata');
points = [x_org; y_org]';
% to rotate 8 degree counterclockwise
theta = 8;
% Rotation matrix
R = [cosd(theta) -sind(theta); sind(theta) cosd(theta)];
% Rotate points
points_rot = R*points';
figure(3)
plot(points_rot(1,:), points_rot(2,:), '.');
Adding this to the end of your code results in the following figure:

Looping my algorithm to plot for a different parameter value on the same graph(MATLAB)

I've implemented an algorithm for my physics project which does exactly what I want. The problem that I'm stuck which is not the Physics content itself hence I think it might be somewhat trivial to explain what my code does. I'm mainly stuck with the way MATLAB's plotting works if I was to loop over the same algorithm to produce similar graphs with a slight change of a value of my parameter. Here's my code below:
clear; clc; close all;
% Parameters:
z_nn = 4; % Number of nearest-neighbour in lattice (square = 4).
z_nnn = 4; % Number of next-nearest-neighbours in lattice (square = 4).
Lx = 40; % Number of sites along x-axis.
Ly = 40; % Number of sites along y-axis.
sigma = 1; % Size of a site (defines our units of length).
beta = 1.2; % Inverse temperature beta*epsilon.
mu = -2.53; % Chemical potential mu/epsilon.
mu_2 = -2.67; % Chemical potential mu/epsilon for 2nd line.
J = linspace(1, 11, 11);%J points for the line graph plot
potential = zeros(Ly);
attract = 1.6; %wall attraction constant
k = 1; %wall depth
rho_0 = 0.4; % Initial density.
tol = 1e-12; % Convergence tolerance.
count = 30000; % Upper limit for iterations.
alpha = 0.01; % Mixing parameter.
conv = 1; cnt = 1; % Convergence value and counter.
rho = rho_0*ones(Ly); % Initialise rho to the starting guess(i-th rho_old) in Eq(47)
rho_rhs = zeros(Ly); % Initialise rho_new to zeros.
% Solve equations iteratively:
while conv>=tol && cnt<count
cnt = cnt + 1; % Increment counter.
% Loop over all lattice sites:
for j=1:Ly
%Defining the Lennard-Jones potential
if j<k
potential(j) = 1000000000;
else
potential(j) = -attract*(j-k)^(-3);
end
% Handle the periodic boundaries for x and y:
%left = mod((i-1)-1,Lx) + 1; % i-1, maps 0 to Lx.
%right = mod((i+1)-1,Lx) + 1; % i+1, maps Lx+1 to 1.
if j<k+1 %depth of wall
rho_rhs(j) = 0;
rho(j) = 0;
elseif j<(20+k)
rho_rhs(j) = (1 - rho(j))*exp((beta*((3/2)*rho(j-1) + (3/2)*rho(j+1) + 2*rho(j) + mu) - potential(j)));
else
rho_rhs(j) = rho_rhs(j-1);
end
end
conv = sum(sum((rho - rho_rhs).^2)); % Convergence value is the sum of the differences between new and current solution.
rho = alpha*rho_rhs + (1 - alpha)*rho; % Mix the new and current solutions for next iteration.
end
% disp(['conv = ' num2str(conv_2) ' cnt = ' num2str(cnt)]); % Display final answer.
% figure(2);
% pcolor(rho_2);
figure(1);
plot(J, rho(1:11));
hold on;
% plot(J, rho_2(1,1:11));
hold off;
disp(['conv = ' num2str(conv) ' cnt = ' num2str(cnt)]); % Display final answer.
figure(3);
pcolor(rho);
Running this code should give you a graph like this
Now I want to produce a similar graph but with one of the variable's value changed and plotted on the same graph. My approach that I've tried is below:
clear; clc; close all;
% Parameters:
z_nn = 4; % Number of nearest-neighbour in lattice (square = 4).
z_nnn = 4; % Number of next-nearest-neighbours in lattice (square = 4).
Lx = 40; % Number of sites along x-axis.
Ly = 40; % Number of sites along y-axis.
sigma = 1; % Size of a site (defines our units of length).
beta = 1.2; % Inverse temperature beta*epsilon.
mu = [-2.53,-2.67]; % Chemical potential mu/epsilon.
mu_2 = -2.67; % Chemical potential mu/epsilon for 2nd line.
J = linspace(1, 10, 10);%J points for the line graph plot
potential = zeros(Ly, length(mu));
gamma = zeros(Ly, length(mu));
attract = 1.6; %wall attraction constant
k = 1; %wall depth
rho_0 = 0.4; % Initial density.
tol = 1e-12; % Convergence tolerance.
count = 30000; % Upper limit for iterations.
alpha = 0.01; % Mixing parameter.
conv = 1; cnt = 1; % Convergence value and counter.
rho = rho_0*[Ly,length(mu)]; % Initialise rho to the starting guess(i-th rho_old) in Eq(47)
rho_rhs = zeros(Ly,length(mu)); % Initialise rho_new to zeros.
figure(3);
hold on;
% Solve equations iteratively:
while conv>=tol && cnt<count
cnt = cnt + 1; % Increment counter.
% Loop over all lattice sites:
for j=1:Ly
for i=1:length(mu)
y = 1:Ly;
MU = mu(i).*ones(Ly)
%Defining the Lennard-Jones potential
if j<k
potential(j) = 1000000000;
else
potential(j) = -attract*(j-k).^(-3);
end
% Handle the periodic boundaries for x and y:
%left = mod((i-1)-1,Lx) + 1; % i-1, maps 0 to Lx.
%right = mod((i+1)-1,Lx) + 1; % i+1, maps Lx+1 to 1.
if j<k+1 %depth of wall
rho_rhs(j) = 0;
rho(j) = 0;
elseif j<(20+k)
rho_rhs(j) = (1 - rho(j))*exp((beta*((3/2)*rho(j-1) + (3/2)*rho(j+1) + 2*rho(j) + MU - potential(j)));
else
rho_rhs(j) = rho_rhs(j-1);
end
end
end
conv = sum(sum((rho - rho_rhs).^2)); % Convergence value is the sum of the differences between new and current solution.
rho = alpha*rho_rhs + (1 - alpha)*rho; % Mix the new and current solutions for next iteration.
disp(['conv = ' num2str(conv) ' cnt = ' num2str(cnt)]); % Display final answer.
figure(1);
pcolor(rho);
plot(J, rho(1:10));
end
hold off;
The only variable that I'm changing here is mu. I would like to loop my first code so that I can enter an arbitrary amount of different values of mu and plot them on the same graph. Naturally I had to change all of the lists dimension from (1 to size of Ly) to (#of mu(s) to size of Ly), such that when the first code is being looped, the i-th mu value in that loop is being turned into lists with dimension as long as Ly. So I thought I would do the plotting within the loop and use "hold on" encapsulating the whole loop so that every plot that was generated in each loop won't be erased. But I've been spending hours on trying to figure out the semantics of MATLAB but ultimately I can't figure out what to do. So hopefully I can get some help on this!
hold on only applies to the active figure, it is not a generic property shared among all figures. What is does is changing the value of the current figure NextPlot property, which governs the behavior when adding plots to a figure.
hold on is equivalent to set(gcf,'NextPlot','add');
hold off is equivalent to set(gcf,'NextPlot','replace');
In your code you have:
figure(3); % Makes figure 3 the active figure
hold on; % Sets figure 3 'NextPlot' property to 'add'
% Do some things %
while conv>=tol && cnt<count
% Do many things %
figure(1); % Makes figure 1 the active figure; 'hold on' was not applied to that figure
plot(J, rho(1:10)); % plots rho while erasing the previous plot
end
You should try to add another hold on statement after figure(1)
figure(1);
hold on
plot(J, rho(1:10));

Line fitting using RANSAC

I am doing a project in image processing, basically to Vectorise hand drawn images using image processing techniques.
I am using RANSAC in my project. The challenge that I am facing is that the algorithm does not perform the best fit as required but
it uses any two random points and draws a line that joins them as shown in the image below.
RANSAC results
In my algorithm to Vectorise hand drawn images, I also did Grey-scaling, Image thresholding (Image Binarization),
and Skeletonization using Morphological Operators.
I am using MATLAB for my project.
The following is the code I have done so far
% Line fitting using RANSAC
[x, y] =size(skeleton_image);
point =[];
count =1;
% figure; imshow(~data); hold on
for n =1:x
for m =1:y
if skeleton_image(n,m)==1
point(count,1)=m;
point(count,2)=n;
count= count+1;
end
end
end
data = point';
number = size(data,2); % Total number of points
X = 1:number;
iter=100; num=2; thresh = 1000;count_inlines=103; best_count=0; best_line=[];
for i=1:iter
% Randomly select 2 points
ind = randi(number,num); % randperm(number,num);
rnd_points= data(:,ind);
% Fitting line
Gradient = (rnd_points(2,2)-rnd_points(2,1))/(rnd_points(1,2)-rnd_points(1,1));
Constant = rnd_points(2,1)-Gradient*rnd_points(1,1);
Line = Gradient*X+Constant; [j,k]=size(Line);
% How many pixels are in the line?
for i=1:number
Distance = sqrt((Line(:,i)-data(1,i)).^2)+(Line(:,i)-data(2,i)).^2);
if Distance<=thresh
inlines = data(:,i);
count_inlines=countinlines+1;
best_line=Line;
end
I think your issue might be in the way you are counting the distance and/or the threshold that is currently 1000. It might choose all the points in any case and just pick the first or the last ransac line.
% Line fitting using RANSAC
%create skeleton_image objects
skeleton_image = zeros(50,50);
% draw a circle
circle_center = [15,15];
radius = 6;
for i=1:50
for j = 1:50
if abs( radius - sqrt( (i-circle_center(1))^2 + (j-circle_center(2))^2 ) ) <0.5 % < controls the thickness of the circle
skeleton_image(i,j) = 1;
endif
end
end
% draw a line
grad=0.5;
dy = 20;
for i=10:50
skeleton_image(ceil(dy + grad*i),i)=1;
if (i < 50)
skeleton_image(ceil(dy + grad*i)+1,i)=1;
endif
end
% a handful of random points to make it more realistic
skeleton_image(20,22)=1;
skeleton_image(30,7)=1;
skeleton_image(18,45)=1;
skeleton_image(10,10)=1;
skeleton_image(20,23)=1;
skeleton_image(31,6)=1;
skeleton_image(19,45)=1;
skeleton_image(9,13)=1;
skeleton_image(20,24)=1;
skeleton_image(31,5)=1;
skeleton_image(18,46)=1;
% [x, y] =size(skeleton_image);
x = 50;
y = 50;
points =[];
count =1;
for n =1:x
for m =1:y
if skeleton_image(n,m)==1
points(count,1)=m;
points(count,2)=n;
count= count+1;
end
end
end
best_line = [];
best_count = 0;
line_point_list = [];
% how close the pixel has to be to the line to be accepted
threshold = 1;
% how many samples are taken
steps = 10;
for i=1:steps
% pick two points
ind1 = randi(number,1);
ind2 = randi(number,1);
point1 = points(ind1,:);
point2 = points(ind2,:);
%auxiliaries
line = [point1;point2];
lpl = []; %line_point_list
count_i = 0;
if point1 != point2
vector1 = point2-point1;
% unit vector
vector1_normalized = vector1 ./ norm(vector1);
% normal direction of the line
normal_of_vector1 = [vector1_normalized(2), -vector1_normalized(1)];
% loop over points
for j = 1:size(points)
% calculate distance
normal_of_vector1;
vector2 = points(j,:) - point1;
distance = abs(dot(vector2, normal_of_vector1));
if ( distance < threshold )
count_i +=1;
lpl(count_i,:) = points(j,:);
endif
end
endif
if ( count_i > best_count)
best_count = count_i;
best_line = line;
line_point_list = lpl;
endif
end
%best_c
%best_l
%line_point_list
% draw found points
for i=1:size(line_point_list)
skeleton_image(line_point_list(i,2),line_point_list(i,1) ) = 0.25;
end
%visualize
figure(1)
imshow(skeleton_image)

Create a plane of points from a row of points

I am trying to create a "plane", so to speak, of points in MATLAB from a set of initial points. I have so far been able to create only one row of points, with the algorithm shown below:
% Generate molecular orientation and position
a = 4.309; % lattice constant in angstroms
l = 10; % number of lattices desired
placeHolder = [0 0 0 ; a/2 a/2 0; a/2 0 a/2; 0 a/2 a/2]; % centers of molecules
numMol = 4; %input('how many molecules are in the unit cell? \n # molecules = ');
numAtoms = 2; %input('how many atoms per molecule? \n # atoms per molecule = ');
atomPerUC = numMol*numAtoms; % number of atoms per unit cell
dir = zeros(numMol,3); % array for orientations
atomPosition = zeros(numAtoms*l^3,3,numMol); % array for positions of atoms
theta = zeros(numMol,1); % array for theta values
phi = zeros(numMol,1); % array for phi values
b = 1.54; % bond length in angstroms
for kk = 1:numMol % generate unit cell
% disp(['What is the molecular orientation for molecule ',num2str(kk),' ?']);
% dir(kk,1) = input('u = '); % ask for user input for molecular orientations
% dir(kk,2) = input('v = ');
% dir(kk,3) = input('w = ');
dir = [1,1,1;-1,1,1;-1,-1,1;1,-1,1];
u = dir(kk,1); % set variables for theta, phi computation
v = dir(kk,2);
w = dir(kk,3);
theta(kk) = w/sqrt(u^2+v^2+w^2); % theta value for molecule k
if v<0 % phi value for molecule k
phi(kk) = 2*pi - acos(abs(v)/sqrt(u^2+v^2+w^2));
else if v>0
phi(kk) = acos(u/sqrt(u^2+v^2+w^2));
end
end
theta = theta(kk); phi = phi(kk); % set variables for theta, phi for x,y,z computation
xp = placeHolder(kk,1); % cooridnates of center of molecule k
yp = placeHolder(kk,2);
zp = placeHolder(kk,3);
x1 = (b/2)*sin(theta)*cos(phi) + xp; % cooridnates for atoms in molecule
x2 = -(b/2)*sin(theta)*cos(phi) + xp;
y1 = (b/2)*sin(theta)*sin(phi) + yp;
y2 = -(b/2)*sin(theta)*sin(phi) + yp;
z1 = (b/2)*cos(theta) + zp;
z2 = -(b/2)*cos(theta) + zp;
atomPosition(1,:,kk) = [x1 y1 z1];
atomPosition(2,:,kk) = [x2 y2 z2];
end
for k = 1:numMol
x01 = atomPosition(1,1,k); y01 = atomPosition(1,2,k); z01 = atomPosition(1,3,k);
x02 = atomPosition(2,1,k); y02 = atomPosition(2,2,k); z02 = atomPosition(2,3,k);
for ii = 1:l-1
atomPosition(2*ii+1,:,k) = [(atomPosition(2*ii-1,1,k) + a) y01 z01];
atomPosition(2*ii+2,:,k) = [(atomPosition(2*ii,1,k) + a) y02 z02];
end
end
My problem is that I do not know how to, from here, turn this "row" of points into a "plane" of points. This can be thought of as taking the points that are known on the x-axis, and creating similar rows moving up in the y-direction to create an x-y plane of points.
Any help/suggestions would be appreciated!
Though I do not understand exactly what you are trying to do. In a simple case you can move from a row of points to a plane by adding the extra dimension.
ie.
x=[1,2,3,4,5]
y=x^2
changes to
x=[1,2,3,4,5]
y=[1,2,3,4,5]
[x,y] = meshgrid(x,y)
z=x^2+y^2

How can I modify the colors on MATLAB's colorbar

I am plotting the azimuth and elevation of some satellites, where the color of each trajectory represents the S4 index, from low (blue) to high (red). I would like however, to be able to format the colors and corresponding values, so that more of the lower effects of scintillation can actually be distinguished. This is because the high end of scintillation (red) only shows one or two points. Here is a picture of the trajectory and the code.
clc; close all; clear all
load combo_323_full
circular_plot
x = [];
y = [];
for s = 1:samples
% plot each satellite location for that sample
for sv = 1:sats
% check if positive or negative elevation
if (elevation((s - 1) * sats + sv) < 0)
elNeg = 1;
else
elNeg = 0;
end
% convert to plottable cartesian coordinates
el = elevation((s - 1) * sats + sv);
az = azimuth((s - 1) * sats + sv);
x = [x;(pi/2-abs(el))/(pi/2).*cos(az-pi/2)];
y = [y;-1*(pi/2-abs(el))/(pi/2).*sin(az-pi/2)];
% check for final sample
% if (s == samples)
% plot(x,y,'r*');
% text(x,y+.07,int2str(SVs(sv)), ...
% 'horizontalalignment', ...
% 'center','color','r');
% else
% check for +/- elevation
% if (elNeg == 0)
% plot(x,y,'.','color',rgb('DarkBlue'));
% else
% plot(x,y,'g.');
% % end
% end
end
end
z = combo(:,5);
for j = 1:10
% hold on
% circular_plot
lRef = length(x);
l1 = floor(lRef*(1/100));
l2 = floor(l1*j);
x_time = x(1:l2);
y_time = y(1:l2);
zr = z(1:l2);
navConstants;
% find out from 'plotMat' if plotting satellite locations or trajectories in
% addition determine how many satellites are being tracked and how many
% samples for each satellite (# samples / satellite must always be equal)
gpsTime = combo(1,2);
i = 1;
t = gpsTime;
while ((i ~= size(combo,1)) & (t == gpsTime))
i = i + 1;
t = combo(i,2);
end
if (t == gpsTime)
sats = i;
else
sats = i - 1;
end;
samples = size(combo,1) / sats;
SVs = combo(1:sats,1);
elevation = combo(:,20).*pi/180;
azimuth = combo(:,19).*pi/180;
% initialize polar - plotting area
figure(j);
axis([-1.4 1.4 -1.1 1.1]);
axis('off');
axis(axis);
hold on;
% plot circular axis and labels
th = 0:pi/50:2*pi;
x_c = [ cos(th) .67.*cos(th) .33.*cos(th) ];
y_c = [ sin(th) .67.*sin(th) .33.*sin(th) ];
plot(x_c,y_c,'color','w');
text(1.1,0,'90','horizontalalignment','center');
text(0,1.1,'0','horizontalalignment','center');
text(-1.1,0,'270','horizontalalignment','center');
text(0,-1.1,'180','horizontalalignment','center');
% plot spoke axis and labels
th = (1:6)*2*pi/12;
x_c = [ -cos(th); cos(th) ];
y_c = [ -sin(th); sin(th) ];
plot(x_c,y_c,'color','w');
text(-.46,.93,'0','horizontalalignment','center');
text(-.30,.66,'30','horizontalalignment','center');
text(-.13,.36,'60','horizontalalignment','center');
text(.04,.07,'90','horizontalalignment','center');
scatter(x_time,y_time,3,zr)
colorbar
axis equal
end
You can make your own colormap, it's just a N by 3 matrix where the columns are the red, green and blue components respectively.
The default colormap is jet. If you type for instance
>>> jet(16)
you will get a 16 by 3 matrix and you can see how it is made.
Then use colormap(your_own_colormap) to change it.