How to run a matrix column by column in Matlab? - matlab

I am running a matrix off of a nested for loop. My problem here is that the values come out wrong because the loop fills the matrix row by row. I would like to have the loop fill the matrix column by column to avoid this issue.
T_i = 85; %Initial temperature (K)
T_inf = 20; %Free stream temperature (K)
h = 50; %Convection heat transfer coefficient (W/m^2K)
alp = 0.0000015; %Thermal diffusivity (m^2/s)
k = 15; %Thermal conductivity (W/mK)
del_x = 0.03; %Incremental distance between center nodes (m)
del_t = 300; %Incremental time diference (s)
Fo = alp*del_t/(del_x^2) %Find the Numerical/Discretized Fourier Number
Bi = h*del_x/k %Find the Numerical/Discretized Biot Number
T__vec = [85;85;85;85] %Initial temperature vector for 4 node points.
%T_inf_vec = 20+zeros(1:10)
M=5 %No. of rows
N=10 %No. of columns
T_inf_vec = [20,20,20,20,20,20,20,20,20,20]
A=zeros(M,N);
A(1:4)= T__vec;
A = [T_inf_vec;A];
for i=2:M
for j=2:N
T_p1=(2*Fo*A(i+1,j-1))+(2*Bi*Fo*A(i-1,j-1))+(((1-2*Fo)-(2*Bi*Fo))*A(i,j-1))
T_p11 = Fo*A(i-1,j-1)-2*Fo*A(i,j-1)+A(i,j-1)+Fo*A(i+1,j-1);
if i==2
A(i,j)= T_p1
elseif i<1
A(i,j)= 20
else
A(i,j)= T_p11
end
end
end

Change the for loop by:
for j=2:M
for i=2:N
T_p1=(2*Fo*A(i+1,j-1))+(2*Bi*Fo*A(i-1,j-1))+(((1-2*Fo)-(2*Bi*Fo))*A(i,j-1))
T_p11 = Fo*A(i-1,j-1)-2*Fo*A(i,j-1)+A(i,j-1)+Fo*A(i+1,j-1);
if i==2
A(i,j)= T_p1
elseif i<1
A(i,j)= 20
else
A(i,j)= T_p11
end
end
end

Related

How do I fix my code to find the convergence rate

The IBVP is
u_t+2u_x=0 , 0<x<1, t>0
u(x,0)=sin(pi*x)
u(0,t)=g(t)=sin(-2*pi*t)
I have to first implement the scheme using 4th-order central difference SBP operator in space and RK4 in time with spacing xi=i*h, i=0,1,...,N and update g(t) at every RK stage. Also, using the code compute the convergence rate on a sequence of grids.
Below I have shown my working which is not helping me find the convergence rate so can anyone help me with finding my mistakes.
%Parameters
nstp = 16; %number of grid points in space
t0 = 0; %initial time
tend = 1; %end time
x0 = 0; %left boundary
xN = 1; %right boundary
x = linspace(0,1,nstp); %points in space
h = xN-x0/nstp-1; %grid size
cfl = 4;
k = cfl*h; %length of time steps
N = ceil(tend/k); %number of steps in time
k = tend/N; %length of time steps
u0 = sin(pi*x); %initial data
e = zeros(nstp);
e(1) = 1;
e0 = e(:,1);
m = zeros(nstp);
m(1) = sin(-2*pi*tend);
g = m(:,1);
%4th order central SBP operator in space
m=10; %points
H=diag(ones(m,1),0);
H(1:4,1:4)=diag([17/48 59/48 43/48 49/48]);
H(m-3:m,m-3:m)=fliplr(flipud(diag([17/48 59/48 43/48 49/48])));
H=H*h;
HI=inv(H);
D1=(-1/12*diag(ones(m-2,1),2)+8/12*diag(ones(m-1,1),1)- ...
8/12*diag(ones(m-1,1),-1)+1/12*diag(ones(m-2,1),-2));
D1(1:4,1:6)=[-24/17,59/34,-4/17,-3/34,0,0; -1/2,0,1/2,0,0,0;
4/43,-59/86,0,59/86,-4/43,0; 3/98,0,-59/98,0,32/49,-4/49];
D1(m-3:m,m-5:m)=flipud( fliplr(-D1(1:4,1:6)));
D1=D1/h;
%SBP-SAT scheme
u = -2*D1*x(1:N-1)'-(2*HI*(u0-g)*e);
%Runge Kutta for ODE
for i=1:nstp %calculation loop
t=(i-1)*k;
k1=D*u;
k2=D*(u+k*k1/2);
k3=D*(u+k*k2/2);
k4=D*(u+k*k3);
u=u+(h*(k1+k2+k3+k4))/6; %main equation
figure(1)
plot(x(1:N-1),u); %plot
drawnow
end
%error calculcation
ucorrect = sin(pi*(x-2*tend)); %correct solution
ucomp = u(:,end); %computed solution
errornorm = sqrt((ucomp-ucorrect)'*H*(ucomp-ucorrect)); %norm of error**
One egregious error is
h = xN-x0/nstp-1; %grid size
You need parentheses here, else you compute h as xN-(x0/nstp)-1=1-(0/nstp)-1=0.
Or avoid this all and use the actual grid step. Also, if nstp is the number of steps or segments in the subdivision, the number of nodes is one larger. And if you define x0,xN then you should also actually use them.
x = linspace(x0,xN,nstp+1); %points in space
h = x(2)-x(1); %grid size
As to the SBP-SAT approach, the space discretization gives
u_t(t) + 2*D_1*u(t) = - H_inv * (dot(e_0,u(t)) - g(t))*e_0
which should give the MoL ODE function as
F = #(u,t) -2*D1*u - HI*e0*(u(1)-g(t))
The matrix construction has to be adapted to have the correct extends for these changed operations.
The implement RK4 as
k1 = F(u,t)
k2 = F(u+0.5*h*k1, t+0.5*h)
...
In total this gives a modified script below. Stable solutions only occur for cfl=1 or below. With that the errors seemingly behave like 4th order. The factor for the initial condition also works best in the range 0.5 to 1, larger factors tend to increase the error at x=0, at least in the initial time steps. With the smaller factors the error is uniform over the interval.
%Parameters
xstp = 16; %number of grid points in space
x0 = 0; %left boundary
xM = 1; %right boundary
x = linspace(x0,xM,xstp+1)'; %points in space
h = x(2)-x(1); %grid size
cfl = 1;
t0 = 0; %initial time
tend = 1; %end time
k = cfl*h; %length of time steps
N = ceil(tend/k); %number of steps in time
k = tend/N; %length of time steps
u = sin(pi*x); %initial data
e0 = zeros(xstp+1,1);
e0(1) = 1;
g = #(t) sin(-2*pi*t);
%4th order central SBP operator in space
M=xstp+1; %points
H=diag(ones(M,1),0); % or eye(M)
H(1:4,1:4)=diag([17/48 59/48 43/48 49/48]);
H(M-3:M,M-3:M)=fliplr(flipud(diag([17/48 59/48 43/48 49/48])));
H=H*h;
HI=inv(H);
D1=(-1/12*diag(ones(M-2,1),2)+8/12*diag(ones(M-1,1),1)- ...
8/12*diag(ones(M-1,1),-1)+1/12*diag(ones(M-2,1),-2));
D1(1:4,1:6) = [ -24/17, 59/34, -4/17, -3/34, 0, 0;
-1/2, 0, 1/2, 0, 0, 0;
4/43, -59/86, 0, 59/86, -4/43, 0;
3/98, 0, -59/98, 0, 32/49, -4/49 ];
D1(M-3:M,M-5:M) = flipud( fliplr(-D1(1:4,1:6)));
D1=D1/h;
%SBP-SAT scheme
F = #(u,t) -2*D1*u - 0.5*HI*(u(1)-g(t))*e0;
clf;
%Runge Kutta for ODE
for i=1:N %calculation loop
t=(i-1)*k;
k1=F(u,t);
k2=F(u+0.5*k*k1, t+0.5*k);
k3=F(u+0.5*k*k2, t+0.5*k);
k4=F(u+k*k3, t+k);
u=u+(k/6)*(k1+2*k2+2*k3+k4); %main equation
figure(1)
subplot(211);
plot(x,u,x,sin(pi*(x-2*(t+k)))); %plot
ylim([-1.1,1.1]);
grid on;
legend(["computed";"exact"])
drawnow
subplot(212);
plot(x,u-sin(pi*(x-2*(t+k)))); %plot
grid on;
hold on;
drawnow
end
%error calculcation
ucorrect = sin(pi*(x-2*tend)); %correct solution
ucomp = u; %computed solution
errornorm = sqrt((ucomp-ucorrect)'*H*(ucomp-ucorrect)); %norm of error**

how run kmean algorithm on sift keypoint in matlab

I need to run the K-Means algorithm on the key points of the Sift algorithm in MATLAB .I want to cluster the key points in the image but I do not know how to do it.
First, put the key points into X with x coordinates in the first column and y coordinates in the second column like this
X=[reshape(keypxcoord,numel(keypxcoord),1),reshape(keypycoord,numel(keypycoord),1))]
Then if you have the statistical toolbox, you can just use the built in 'kmeans' function lik this
output = kmeans(X,num_clusters)
Otherwise, write your own kmeans function:
function [ min_group, mu ] = mykmeans( X,K )
%MYKMEANS
% X = N obervations of D element vectors
% K = number of centroids
assert(K > 0);
D = size(X,1); %No. of r.v.
N = size(X,2); %No. of observations
group_size = zeros(1,K);
min_group = zeros(1,N);
step = 0;
%% init centroids
mu = kpp(X,K);
%% 2-phase iterative approach (local then global)
while step < 400
%% phase 1, batch update
old_group = min_group;
% computing distances
d2 = distances2(X,mu);
% reassignment all points to closest centroids
[~, min_group] = min(d2,[],1);
% recomputing centroids (K number of means)
for k = 1 : K
group_size(k) = sum(min_group==k);
% check empty group
%if group_size(k) == 0
assert(group_size(k)>0);
%else
mu(:,k) = sum(X(:,min_group==k),2)/group_size(k);
%end
end
changed = sum(min_group ~= old_group);
p1_converged = changed <= N*0.001;
%% phase 2, individual update
changed = 0;
for n = 1 : N
d2 = distances2(X(:,n),mu);
[~, new_group] = min(d2,[],1);
% recomputing centroids of affected groups
k = min_group(n);
if (new_group ~= k)
mu(:,k)=(mu(:,k)*group_size(k)-X(:,n));
group_size(k) = group_size(k) - 1;
mu(:,k)=mu(:,k)/group_size(k);
mu(:,new_group) = mu(:,new_group)*group_size(new_group)+ X(:,n);
group_size(new_group) = group_size(new_group) + 1;
mu(:,new_group)=mu(:,new_group)/group_size(new_group);
min_group(n) = new_group;
changed = changed + 1;
end
end
%% check convergence
if p1_converged && changed <= N*0.001
break;
else
step = step + 1;
end
end
end
function d2 = distances2(X, mu)
K = size(mu,2);
N = size(X,2);
d2 = zeros(K,N);
for j = 1 : K
d2(j,:) = sum((X - repmat(mu(:,j),1,N)).^2,1);
end
end
function mu = kpp( X,K )
% kmeans++ init
D = size(X,1); %No. of r.v.
N = size(X,2); %No. of observations
mu = zeros(D, K);
mu(:,1) = X(:,round(rand(1) * (size(X, 2)-1)+1));
for k = 2 : K
% computing distances between centroids and observations
d2 = distances2(X, mu(1:k-1));
% assignment
[min_dist, ~] = min(d2,[],1);
% select new centroids by selecting point with the cumulative dist
% value (distance) larger than random value (falls in range between
% dist(n-1) : dist(n), dist(0)= 0)
rv = sum(min_dist) * rand(1);
for n = 1 : N
if min_dist(n) >= rv
mu(:,k) = X(:,n);
break;
else
rv = rv - min_dist(n);
end
end
end
end

Align right-shifted waveforms (action potentials)

enter image description here
I am having difficulty with my code aligning right shifted waveforms by the minimum peak point. In the left shifted, I copy the difference in indices between the desired minimum point and the given one to left of the waveform, and then delete those extra points after once this aligns the waveform. However, the same technique is not working for the right shifted ones. Any help would be much appreciated! Input (vals) is any n x 97 matrix.
function [vals] = align_wvs(wvs)
%Align_wvs - Align waveforms to minimum point
%
%align_wvs(wvs)
%
%wvs - matrix of waveforms
%
%Returns 'vals' - newly aligned matrix of waveforms
wvfrms = (wvs*10^6); %convert to microvolts
wvfrms = wvfrms(:,all(~isnan(wvfrms)));
min_pt = min(wvfrms(:)); %find minimum point in wvs
[~,col] = find(wvfrms==min_pt); %find index of min poin
if numel(col)>1
col = col(1);
end
%and that of other wvfrms
vals = zeros(size(wvfrms)); %matrix of size wvfrms, vals
for i = 1:size(vals,1) %for length of input
vals(i,:) = wvfrms(i,:); %copy og wvfrm into vals
nums = vals(i,:); %get second copy
ind_min = min(nums);
[~,colmin] = find(nums==ind_min);
diff_col = col-colmin;
if (diff_col~=0) %if difference is not = 0
if (diff_col>0) %if wvfrm is shifted to the left
inds = nums(1:diff_col); %copy first n values of nums, where n is diff_rows
new_length = length(nums)+length(inds); %extend wvfrm by amount ind
new_vals = zeros(1,new_length); %create new array of size new_length
new_vals(1:(diff_col)) = inds; %add inds to begining of new array
new_vals(diff_col+1:end) = nums; %add nums to rest of array
new_vals(1:(diff_col)) = [];%delete diff_rows-1 values from end
vals(i,:) = new_vals; %add to values
else %if wvfrm is shifted to the right
inds = nums(end+(diff_col+1):end); %copy last n values of nums, where n is diff_rows
new_length = length(nums)+length(inds); %extend wvfrm by amount ind
new_vals = zeros(1,new_length); %create new array of size new_length
new_vals(end+(diff_col+1):end) = inds;%add inds to end of new array
new_vals(1:(end+(diff_col))) = nums;%add nums to rest of array
new_vals(1:(diff_col*-1)) = []; %delete diff_rows-1 values from begining
vals(i,:) = new_vals; %add to values
end
end
end
end
List item
Does replacing the if (diff_col~=0) block with the following work?
if (diff_col~=0)
if (diff_col>0)
vals(i,:) = [zeros(1,diff_col) nums(1:(end-diff_col))];
else
vals(i,:) = [nums((-diff_col+1):end) zeros(1,-diff_col)];
end
end

Kmeans too many centroids being plotted

I am trying to plot clusters via the MATLAB function kmean but am getting way too many centroids and have no idea why. Here is my code and an example of a figure:
rng(1);
wv_prop = [min_pts(:) slope(:)];
if (isempty(wv_prop)==0)
[idx,C] = kmeans(wv_prop,2);
subplot(3,2,5);
plot(wv_prop(idx==1,1),wv_prop(idx==1,2),'b.','MarkerSize',12);
hold on
plot(wv_prop(idx==2,1),wv_prop(idx==2,2),'r.','MarkerSize',12);
plot(C(:,1),C(:,2),'kx',...
'MarkerSize',15,'LineWidth',3)
Here is an example of the data I use:
wv_prop:
-7.50904246127179e-05 2.52737793199461e-05
-7.64715493632322e-05 -29.2845021783221
-8.16630514296111e-05 -15.5896244315076
-8.60516901697005e-05 3.87325886247646e-05
-9.07390060961131e-05 4.06844795948271e-05
-7.93980060844007e-05 3.72806601486833e-05
-8.08420950480078e-05 3.81372062193057e-05
-8.53045358845788e-05 4.00072285969318e-05
-7.07712622172574e-05 3.55502071296987e-05
-8.02846575361635e-05 3.91085777803079e-05
-8.82904795076420e-05 4.21557386394776e-05
-8.32088783242009e-05 4.08103587885502e-05
-8.17564769131708e-05 4.06201592898485e-05
-8.88574631122910e-05 4.31980154605407e-05
-9.55496137235401e-05 4.55119867638717e-05
-7.11241881995855e-05 3.72772062250438e-05
-8.20641318582800e-05 6.09118479264444e-05
-7.92369664739745e-05 5.86246041439769e-05
-7.61219361068837e-05 5.57318660221894e-05
-8.52918510230295e-05 5.84710267850959e-05
-8.99668387994064e-05 5.84558301867090e-05
-9.62926333243702e-05 5.87762601336998e-05
-7.87678776488358e-05 4.67111894400931e-05
-7.53525297201741e-05 4.13207831828739e-05
-7.71766983561651e-05 3.82625914011195e-05
-9.03499693359608e-05 4.06874790212135e-05
-7.59387077492098e-05 2.92390401569819e-05
-7.97649576465785e-05 32.1683359898974
-8.06408560217508e-05 1.55409105433306e-05
-8.10515208048491e-05 1.31180389653758e-05
-7.70540121076476e-05 9.43353748786386e-06
-7.24001267378072e-05 5.78599898248438e-06
-8.93350436455590e-05 9.61034087028361e-06
-7.97722332494743e-05 4.89104076311932e-06
-8.40022599007737e-05 5.06726288587479e-06
-7.89655937936233e-05 2.44686642783556e-06
-8.58007004774045e-05 4.06628163987085e-06
-7.68775819259902e-05 1.06146142996962e-06
-7.05769224846652e-05 -2.25666633700963e-06
-7.73022200637920e-05 1.34546072255262e-06
-7.65784897728499e-05 1.62917829786978e-06
-7.41548367397790e-05 1.46536230997079e-06
-9.17371298592096e-05 1.17025036839378e-05
-7.35354500231489e-05 4.43710161064086e-06
function [] = Select_Figs(filename,startblock,endblock,startclust,endclust,animal,day)
%Select_Figs - Plots average waveforms, standard deviation, difference over time,
%fitted peak location histogram, mean squared error, k-mean clustered peak location and slope,
%and raw waveforms across selected blocks and clusters,
%saves to folder Selected-Figures-animal-date
%
%Select_Figs(filename,startblock,endblock,startclust,endclust,animal,date)
%
%filename - Sort.mat(e.g. = 'Sort.mat')
%
%startblock- first block (e.g. = 7)
%
%endblock - last block (e.g. = 12)
%
%startclust - first cluster (e.g. = 5)
%
%endclust - last cluster (e.g. = 10)
%
%animal - animal number (e.g. = 12)
%
%date - start of experiment (e.g. = 101617)
%
%Function called by User_Sort.m
Sort = filename;
addpath(pwd);
%Get Sort file
foldername = sprintf('Selected-Figures-%s-%s',animal,day); %Creates dynamic folder name to store figures
mkdir(foldername); %Makes directory
cd(fullfile(foldername)); %Cd to new directory
tvec = 0:.013653333:(.013653333*97); %Time vector
t = tvec(2:end);
for clust = startclust:endclust %Loops through all clusters
fig = cell(1,endblock); %Preallocate # of figures
name = sprintf('Idx_%d',clust); %Individual cluster name
fig{clust} = figure('Visible', 'off'); %Turns figure visibility off
for block = startblock:endblock %Loop through all blocks
wvfrms_avg =Sort.(name)(block).avg;
wvfrms_avg_scaled = (wvfrms_avg*10^6);
wvfrms_std =Sort.(name)(block).standdev;
min_ind = wvfrms_avg_scaled == min(wvfrms_avg_scaled);
min_loc = t(min_ind);
[~,io] = findpeaks(wvfrms_avg_scaled);
leftmin = io<find(wvfrms_avg_scaled==min(wvfrms_avg_scaled));
leftmin = leftmin(leftmin~=0);
rightmin = io>find(wvfrms_avg_scaled==min(wvfrms_avg_scaled));
rightmin = rightmin(rightmin~=0);
if (isempty(wvfrms_avg_scaled)==0)
subplot(3,2,1);
if (isnan(wvfrms_avg_scaled)==0)&((-30<min(wvfrms_avg_scaled))||(min_loc>0.55)||(min_loc<0.3)||(length(io(leftmin))>2)||(length(io(rightmin))>2))
plot(tvec(1:end-1),wvfrms_avg_scaled,'r');
else
plot(tvec(1:end-1),wvfrms_avg_scaled,'b');
end
end
new_wv = wvfrms_avg_scaled(40:end);
[~,locs_scaled] = findpeaks(new_wv);
if isempty(locs_scaled)==1
ind_scaled = max(new_wv);
else
ind_scaled = locs_scaled(1);
end
x1_scaled = new_wv(find(min(wvfrms_avg_scaled)));
y1_scaled = min(wvfrms_avg_scaled);
x2_scaled = ind_scaled;
y2_scaled = new_wv(find(ind_scaled));
slope_scaled= (y2_scaled-y1_scaled)./(x2_scaled-x1_scaled);
if (isnan(wvfrms_avg_scaled)==0)
if ((-30<min(wvfrms_avg_scaled)))
lab = sprintf('Time (ms) \n Peak exceeds amplitude range (%s)',num2str(min(wvfrms_avg_scaled)));
xlabel(lab,'FontSize',8);
ylabel('Mean Voltage (\muV)','FontSize',8);
title('Average Waveform','FontSize',8);
elseif ((min_loc>0.55)||(min_loc<0.3))
lab = sprintf('Time (ms) \n Peak location exceeds range (Time = %s)',num2str(min_loc));
xlabel(lab,'FontSize',8);
ylabel('Mean Voltage (\muV)','FontSize',8);
title('Average Waveform','FontSize',8);
elseif (length(io(leftmin))>2)||(length(io(rightmin))>2)
lab = sprintf('Time (ms) \n Peak limit exceeded (# = %s) Peak = %s',num2str(length(io)),num2str(min(wvfrms_avg_scaled)));
xlabel(lab,'FontSize',8);
ylabel('Mean Voltage (\muV)','FontSize',8);
title('Average Waveform','FontSize',8);
else
lab = sprintf('Time (ms) \n Peak = %s Slope = %s',num2str(min(wvfrms_avg_scaled)),num2str(slope_scaled));
xlabel(lab,'FontSize',8)
ylabel('Mean Voltage (\muV)','FontSize',8);
title('Average Waveform','FontSize',8);
end
end
if (isempty(wvfrms_std)==0&isempty(wvfrms_avg)==0)
subplot(3,2,2);
errorbar(t,wvfrms_avg,wvfrms_std); %Plots errorbars
end
wvfrms_num_text = sprintf(['Time (ms) \n # Waveforms: ' num2str(size(Sort.(name)(block).block,2))]);
xlabel(wvfrms_num_text,'FontSize',8);
ylabel('Mean Voltage (V)','FontSize',8);
title('Average Waveform + STD','FontSize',8);
wvfrms = Sort.(name)(block).block;
for i = 1:size(wvfrms,1)
if isempty(wvfrms)==0
min_pts = min(wvfrms,[],2); %Adds array of min wvfrm points to matrix
slope = zeros(1,size(wvfrms,1));
new = wvfrms(i,:);
new_cut = new(40:end);
[~,locs] = findpeaks(new_cut);
if isempty(locs)==1
ind = max(new_cut);
else
ind = locs(1);
end
x1 = new(find(min_pts(i)));
y1 = min_pts(i);
x2 = ind;
y2 = new(find(ind));
slope(i) = (y2-y1)./(x2-x1);
else
slope(i) = 0;
end
end
bins = 100;
hist_val = (min_pts(:)*10^6);
if isempty(hist_val)==0
%Convert matrix of min points to array and into microvolts
subplot(3,2,3);
histogram(hist_val,bins);
ylabel('Count','FontSize',8);
title('Waveform Peaks','FontSize',8);
cnt = histcounts(hist_val,bins); %Returns bin counts
line_fit = zeros(1,length(cnt)); %Preallocates vector to hold line to fit histogram
for i = 3:length(line_fit)-3
if (cnt(i)<mean(cnt)) %If bin count is less than mean, take mean of 3
cnt(i)=mean([cnt(i-1) cnt(i+1)]); %consecutive bins, set as bin count
end
if (mean([cnt(i-2) cnt(i-1) cnt(i) cnt(i+1) cnt(i+2)])>=mean(cnt)) %If mean of 5 consecutive bins
line_fit(i-1) = (max([cnt(i-2) cnt(i-1) cnt(i) cnt(i+1) cnt(i+2)]));%exceeds bin count, set max,
end %add to line fit vector
end
line_fit(line_fit<=mean(cnt)) = min(cnt)+1; %Set line_fit values less than mean
x = linspace(min(hist_val),max(hist_val),length(line_fit)); %X axis (min - max point of vals)
hold on
plot(x,line_fit,'k','LineWidth',1.5);
assignin('base','hist_val',hist_val);
if (isempty(hist_val)==0)
gm = fitgmdist(hist_val,2,'RegularizationValue',0.1);
warning('off','stats:gmdistribution:FailedToConverge');
comp1 = gm.ComponentProportion(1)*100;
comp2 = gm.ComponentProportion(2)*100;
mean1 = gm.mu(1);
mean2 = gm.mu(2);
hist_leg = sprintf('\\muV \n Component 1 = %0.2f%% Component 2 = %0.2f%% \n Mean 1 = %0.2f Mean 2 = %0.2f',comp1,comp2,mean1,mean2);
xlabel(hist_leg,'FontSize',8);
end
hold off
else
subplot(3,2,3);
hist_val = 0;
plot(hist_val);
end
hist_val = (slope(:)*10^3);
if isempty(hist_val)==0
subplot(3,2,4);
histogram(hist_val,bins);
ylabel('Count');
cnt = histcounts(hist_val,bins); %Returns bin counts
line_fit = zeros(1,length(cnt)); %Preallocates vector to hold line to fit histogram
for i = 3:length(line_fit)-3
if (cnt(i)<mean(cnt)) %If bin count is less than mean, take mean of 3
cnt(i)=mean([cnt(i-1) cnt(i+1)]); %consecutive bins, set as bin count
end
if (mean([cnt(i-2) cnt(i-1) cnt(i) cnt(i+1) cnt(i+2)])>=mean(cnt)) %If mean of 5 consecutive bins
line_fit(i-1) = (max([cnt(i-2) cnt(i-1) cnt(i) cnt(i+1) cnt(i+2)])); %exceeds bin count, set max,
end %add to line fit vector
end
line_fit(line_fit<=mean(cnt)) = min(cnt)+1; %Set line_fit values less than mean
x = linspace(min(hist_val),max(hist_val),length(line_fit)); %X axis (min - max point of vals)
hold on
plot(x,line_fit,'k','LineWidth',1.5);
gm = fitgmdist(hist_val,2,'RegularizationValue',0.1);
warning('off','stats:gmdistribution:FailedToConverge');
comp1 = gm.ComponentProportion(1)*100;
comp2 = gm.ComponentProportion(2)*100;
mean1 = gm.mu(1);
mean2 = gm.mu(2);
title('Waveform Slope','FontSize',8);
hist_leg = sprintf('Slope (m) \n Component 1 = %0.2f%% Component 2 = %0.2f%% \n Mean 1 = %0.2f Mean 2 = %0.2f',comp1,comp2,mean1,mean2);
xlabel(hist_leg,'FontSize',8);
hold off
else
subplot(3,2,4);
hist_val = 0;
plot(hist_val);
end
rng(1);
wv_prop = [min_pts(:) slope(:)];
if (isempty(wv_prop)==0)
[idx,C] = kmeans(wv_prop,2);
subplot(3,2,5);
plot(wv_prop(idx==1,1),wv_prop(idx==1,2),'b.','MarkerSize',12);
hold on
plot(wv_prop(idx==2,1),wv_prop(idx==2,2),'r.','MarkerSize',12);
plot(C(:,1),C(:,2),'kx',...
'MarkerSize',15,'LineWidth',3)
title('Clustered Peak and Slope','FontSize',8);
fig_about = sprintf('BL%s - Cluster %s Block %s', animal,num2str(clust),num2str(block));
figtitle(fig_about);
else
subplot(3,2,5);
wv_prop = 0;
plot(wv_prop);
end
if isempty(wvfrms)==0
[vals] = align_wvs(wvfrms);
if (~isempty(vals))
subplot(3,2,6);
plot(t,vals);
title('Raw Waveforms','FontSize',8);
end
else
subplot(3,2,6);
w = 0;
plot(w);
end
print(fig{clust},['Cluster-' num2str(clust) ' Block-' num2str(block)],'-dpng');
end
end
disp('Done');
end

Simulate a queue using Lindley's equation in Matlab

I have to simulate a simple queue in Matlab using Lindley's equation:
W_{n+1}^Q = max(0, W_n^Q + S_n - X_{n+1}
I think I have done so, with the following code, but I am trying to run it several times and cannot save the information correct. The variables I want to save at the end of running the simulation are only saving the information from the last attempt (here for m=3).. while I clearly would like to see this for all runs (m=1,2,3).
for m=1:3
l = 1.1; % try this value for lambda
N = 10000; % let 1000 people arrive
X = exprnd(l,[1,N]); % make 1000 exponential interarrivals
S = 2*rand(1,N); % uniform on [0,2]
w = zeros(1,N);
sum1 = zeros(1,m);
avg1 = zeros(1,m);
max1 = zeros(1,m);
for i=1:N
if i==1 % first customer doesn't have to wait
w(i) = 0;
else % following customers follow lindley's equation
w(i) = max(w(i-1) + S(i-1) - X(i), 0); % n-th customer's waiting time
count(i) = w(i) > 15; % count number of times greater than 15
end
end
max1(m) = max(w);
sum1(m) = sum(count); % sum number of times greater than 15
avg1(m) = sum1(m)/N; % divide by 1000 to get probability delay is greater than 15
end
You are initializing sum1, avg1 and max1 inside the for loop so in every iteration, these variables are set to zero (i.e. by initialization). This is the reason you loose your previous iteration value. To avoid this, initialize sum1, avg1 and max1 before you for loop. Refer below code for reference. HTH
sum1 = zeros(1,m);
avg1 = zeros(1,m);
max1 = zeros(1,m);
for m=1:3
l = 1.1; % try this value for lambda
N = 10000; % let 1000 people arrive
X = exprnd(l,[1,N]); % make 1000 exponential interarrivals
S = 2*rand(1,N); % uniform on [0,2]
w = zeros(1,N);
for i=1:N
if i==1 % first customer doesn't have to wait
w(i) = 0;
else % following customers follow lindley's equation
w(i) = max(w(i-1) + S(i-1) - X(i), 0); % n-th customer's waiting time
count(i) = w(i) > 15; % count number of times greater than 15
end
end
max1(m) = max(w);
sum1(m) = sum(count); % sum number of times greater than 15
avg1(m) = sum1(m)/N; % divide by 1000 to get probability delay is greater than 15
end