Matlab argument passing to draw ROC curve - matlab

I want to draw a ROC curve using Matlab. Suppose my true positive rate is 3 and false positive rate is 5. Here the code I have to draw ROC curve.
function [Tps, Fps] = ROC(scores, labels)
%% Sort Labels and Scores by Scores
sl = [scores; labels];
[d1 d2] = sort(sl(1,:));
sorted_sl = sl(:,d2);
s_scores = sorted_sl(1,:);
s_labels = round(sorted_sl(2,:));
%% Constants
counts = histc(s_labels, unique(s_labels));
Tps = zeros(1, size(s_labels,2) + 1);
Fps = zeros(1, size(s_labels,2) + 1);
negCount = counts(1);
posCount = counts(2);
%% Shift threshold to find the ROC
for thresIdx = 1:(size(s_scores,2)+1)
% for each Threshold Index
tpCount = 0;
fpCount = 0;
for i = [1:size(s_scores,2)]
if (i >= thresIdx) % We think it is positive
if (s_labels(i) == 1) % Right!
tpCount = tpCount + 1;
else % Wrong!
fpCount = fpCount + 1;
end
end
end
Tps(thresIdx) = tpCount/posCount;
Fps(thresIdx) = fpCount/negCount;
end
%% Draw the Curve
% Sort [Tps;Fps]
x = Tps;
y = Fps;
% Interplotion to draw spline line
count = 100;
dist = (x(1) - x(size(x,2)))/100;
xx = [x(1):-dist:x(size(x,2))];
% In order to get the interpolations, we remove all the unique numbers
[d1 d2] = unique(x);
uni_x = x(1,d2);
uni_y = y(1,d2);
yy = spline(uni_x,uni_y,xx);
% No value should exceed 1
yy = min(yy, 1);
plot(x,y,'x',xx,yy);
How can I pass arguments for this code? How can I pass my true positive and false positive values? Please help, i am new to Matlab.

Related

How do I find local threshold for coefficients in image compression using DWT in MATLAB

I'm trying to write an image compression script in MATLAB using multilayer 3D DWT(color image). along the way, I want to apply thresholding on coefficient matrices, both global and local thresholds.
I like to use the formula below to calculate my local threshold:
where sigma is variance and N is the number of elements.
Global thresholding works fine; but my problem is that the calculated local threshold is (most often!) greater than the maximum band coefficient, therefore no thresholding is applied.
Everything else works fine and I get a result too, but I suspect the local threshold is miscalculated. Also, the resulting image is larger than the original!
I'd appreciate any help on the correct way to calculate the local threshold, or if there's a pre-set MATLAB function.
here's an example output:
here's my code:
clear;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% COMPRESSION %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read base image
% dwt 3/5-L on base images
% quantize coeffs (local/global)
% count zero value-ed coeffs
% calculate mse/psnr
% save and show result
% read images
base = imread('circ.jpg');
fam = 'haar'; % wavelet family
lvl = 3; % wavelet depth
% set to 1 to apply global thr
thr_type = 0;
% global threshold value
gthr = 180;
% convert base to grayscale
%base = rgb2gray(base);
% apply dwt on base image
dc = wavedec3(base, lvl, fam);
% extract coeffs
ll_base = dc.dec{1};
lh_base = dc.dec{2};
hl_base = dc.dec{3};
hh_base = dc.dec{4};
ll_var = var(ll_base, 0);
lh_var = var(lh_base, 0);
hl_var = var(hl_base, 0);
hh_var = var(hh_base, 0);
% count number of elements
ll_n = numel(ll_base);
lh_n = numel(lh_base);
hl_n = numel(hl_base);
hh_n = numel(hh_base);
% find local threshold
ll_t = ll_var * (sqrt(2 * log2(ll_n)));
lh_t = lh_var * (sqrt(2 * log2(lh_n)));
hl_t = hl_var * (sqrt(2 * log2(hl_n)));
hh_t = hh_var * (sqrt(2 * log2(hh_n)));
% global
if thr_type == 1
ll_t = gthr; lh_t = gthr; hl_t = gthr; hh_t = gthr;
end
% count zero values in bands
ll_size = size(ll_base);
lh_size = size(lh_base);
hl_size = size(hl_base);
hh_size = size(hh_base);
% count zero values in new band matrices
ll_zeros = sum(ll_base==0,'all');
lh_zeros = sum(lh_base==0,'all');
hl_zeros = sum(hl_base==0,'all');
hh_zeros = sum(hh_base==0,'all');
% initiate new matrices
ll_new = zeros(ll_size);
lh_new = zeros(lh_size);
hl_new = zeros(lh_size);
hh_new = zeros(lh_size);
% apply thresholding on bands
% if new value < thr => 0
% otherwise, keep the previous value
for id=1:ll_size(1)
for idx=1:ll_size(2)
if ll_base(id,idx) < ll_t
ll_new(id,idx) = 0;
else
ll_new(id,idx) = ll_base(id,idx);
end
end
end
for id=1:lh_size(1)
for idx=1:lh_size(2)
if lh_base(id,idx) < lh_t
lh_new(id,idx) = 0;
else
lh_new(id,idx) = lh_base(id,idx);
end
end
end
for id=1:hl_size(1)
for idx=1:hl_size(2)
if hl_base(id,idx) < hl_t
hl_new(id,idx) = 0;
else
hl_new(id,idx) = hl_base(id,idx);
end
end
end
for id=1:hh_size(1)
for idx=1:hh_size(2)
if hh_base(id,idx) < hh_t
hh_new(id,idx) = 0;
else
hh_new(id,idx) = hh_base(id,idx);
end
end
end
% count zeros of the new matrices
ll_new_size = size(ll_new);
lh_new_size = size(lh_new);
hl_new_size = size(hl_new);
hh_new_size = size(hh_new);
% count number of zeros among new values
ll_new_zeros = sum(ll_new==0,'all');
lh_new_zeros = sum(lh_new==0,'all');
hl_new_zeros = sum(hl_new==0,'all');
hh_new_zeros = sum(hh_new==0,'all');
% set new band matrices
dc.dec{1} = ll_new;
dc.dec{2} = lh_new;
dc.dec{3} = hl_new;
dc.dec{4} = hh_new;
% count how many coeff. were thresholded
ll_zeros_diff = ll_new_zeros - ll_zeros;
lh_zeros_diff = lh_zeros - lh_new_zeros;
hl_zeros_diff = hl_zeros - hl_new_zeros;
hh_zeros_diff = hh_zeros - hh_new_zeros;
% show coeff. matrices vs. thresholded version
figure
colormap(gray);
subplot(2,4,1); imagesc(ll_base); title('LL');
subplot(2,4,2); imagesc(lh_base); title('LH');
subplot(2,4,3); imagesc(hl_base); title('HL');
subplot(2,4,4); imagesc(hh_base); title('HH');
subplot(2,4,5); imagesc(ll_new); title({'LL thr';ll_zeros_diff});
subplot(2,4,6); imagesc(lh_new); title({'LH thr';lh_zeros_diff});
subplot(2,4,7); imagesc(hl_new); title({'HL thr';hl_zeros_diff});
subplot(2,4,8); imagesc(hh_new); title({'HH thr';hh_zeros_diff});
% idwt to reconstruct compressed image
cmp = waverec3(dc);
cmp = uint8(cmp);
% calculate mse/psnr
D = abs(cmp - base) .^2;
mse = sum(D(:))/numel(base);
psnr = 10*log10(255*255/mse);
% show images and mse/psnr
figure
subplot(1,2,1);
imshow(base); title("Original"); axis square;
subplot(1,2,2);
imshow(cmp); colormap(gray); axis square;
msg = strcat("MSE: ", num2str(mse), " | PSNR: ", num2str(psnr));
title({"Compressed";msg});
% save image locally
imwrite(cmp, 'compressed.png');
I solved the question.
the sigma in the local threshold formula is not variance, it's the standard deviation. I applied these steps:
used stdfilt() std2() to find standard deviation of my coeff. matrices (thanks to #Rotem for pointing this out)
used numel() to count the number of elements in coeff. matrices
this is a summary of the process. it's the same for other bands (LH, HL, HH))
[c, s] = wavedec2(image, wname, level); %apply dwt
ll = appcoeff2(c, s, wname); %find LL
ll_std = std2(ll); %find standard deviation
ll_n = numel(ll); %find number of coeffs in LL
ll_t = ll_std * (sqrt(2 * log2(ll_n))); %local the formula
ll_new = ll .* double(ll > ll_t); %thresholding
replace the LL values in c in a for loop
reconstruct by applying IDWT using waverec2
this is a sample output:

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

How to find Orientation of axis of contour in matlab?

I want to find Orientation, MajorAxisLengthand MinorAxisLength of contour which is plotted with below code.
clear
[x1 , x2] = meshgrid(linspace(-10,10,100),linspace(-10,10,100));
mu = [1,3];
sigm = [2,0;0,2];
xx_size = length(mu);
tem_matrix = ones(size(x1));
x_mesh= cell(1,xx_size);
for i = 1 : xx_size
x_mesh{i} = tem_matrix * mu(i);
end
x_mesh= {x1,x2};
temp_mesh = [];
for i = 1 : xx_size
temp_mesh = [temp_mesh x_mesh{i}(:)];
end
Z = mvnpdf(temp_mesh,mu,sigm);
z_plat = reshape(Z,size(x1));
figure;contour(x1, x2, z_plat,3, 'LineWidth', 2,'color','m');
% regionprops(z_plat,'Centroid','Orientation','MajorAxisLength','MinorAxisLength');
In my opinion, I may have to use regionprops command but I don't know how to do this. I want to find direction of axis of contour and plot something like this
How can I do this task? Thanks very much for your help
Rather than trying to process the graphical output of contour, I would instead recommend using contourc to compute the ContourMatrix and then use the x/y points to estimate the major and minor axes lengths as well as the orientation (for this I used this file exchange submission)
That would look something like the following. Note that I have modified the inputs to contourc as the first two inputs should be the vector form and not the output of meshgrid.
% Compute the three contours for your data
contourmatrix = contourc(linspace(-10,10,100), linspace(-10,10,100), z_plat, 3);
% Create a "pointer" to keep track of where we are in the output
start = 1;
count = 1;
% Now loop through each contour
while start < size(contourmatrix, 2)
value = contourmatrix(1, start);
nPoints = contourmatrix(2, start);
contour_points = contourmatrix(:, start + (1:nPoints));
% Now fit an ellipse using the file exchange
ellipsedata(count) = fit_ellipse(contour_points(1,:), contour_points(2,:));
% Increment the start pointer
start = start + nPoints + 1;
count = count + 1;
end
orientations = [ellipsedata.phi];
% 0 0 0
major_length = [ellipsedata.long_axis];
% 4.7175 3.3380 2.1539
minor_length = [ellipsedata.short_axis];
% 4.7172 3.3378 2.1532
As you can see, the contours are actually basically circles and therefore the orientation is zero and the major and minor axis lengths are almost equal. The reason that they look like ellipses in your post is because your x and y axes are scaled differently. To fix this, you can call axis equal
figure;contour(x1, x2, z_plat,3, 'LineWidth', 2,'color','m');
axis equal
Thank you #Suever. It help me to do my idea.
I add some line to code:
clear
[X1 , X2] = meshgrid(linspace(-10,10,100),linspace(-10,10,100));
mu = [-1,0];
a = [3,2;1,4];
a = a * a';
sigm = a;
xx_size = length(mu);
tem_matrix = ones(size(X1));
x_mesh= cell(1,xx_size);
for i = 1 : xx_size
x_mesh{i} = tem_matrix * mu(i);
end
x_mesh= {X1,X2};
temp_mesh = [];
for i = 1 : xx_size
temp_mesh = [temp_mesh x_mesh{i}(:)];
end
Z = mvnpdf(temp_mesh,mu,sigm);
z_plat = reshape(Z,size(X1));
figure;contour(X1, X2, z_plat,3, 'LineWidth', 2,'color','m');
hold on;
% Compute the three contours for your data
contourmatrix = contourc(linspace(-10,10,100), linspace(-10,10,100), z_plat, 3);
% Create a "pointer" to keep track of where we are in the output
start = 1;
count = 1;
% Now loop through each contour
while start < size(contourmatrix, 2)
value = contourmatrix(1, start);
nPoints = contourmatrix(2, start);
contour_points = contourmatrix(:, start + (1:nPoints));
% Now fit an ellipse using the file exchange
ellipsedata(count) = fit_ellipse(contour_points(1,:), contour_points(2,:));
% Increment the start pointer
start = start + nPoints + 1;
count = count + 1;
end
orientations = [ellipsedata.phi];
major_length = [ellipsedata.long_axis];
minor_length = [ellipsedata.short_axis];
tet = orientations(1);
x1 = mu(1);
y1 = mu(2);
a = sin(tet) * sqrt(major_length(1));
b = cos(tet) * sqrt(major_length(1));
x2 = x1 + a;
y2 = y1 + b;
line([x1, x2], [y1, y2],'linewidth',2);
tet = ( pi/2 + orientations(1) );
a = sin(tet) * sqrt(minor_length(1));
b = cos(tet) * sqrt(minor_length(1));
x2 = x1 + a;
y2 = y1 + b;
line([x1, x2], [y1, y2],'linewidth',2);

How does the choice of the wavelet function impact the speed of cwt()?

In cwt() I can specify which wavelet function to use. How does that impact the speed of cwt()?
Here is a benchmark, which I run with the -singleCompThread option when starting MATLAB to force it to use a single computational thread. cwt() was passed a 1,000,000-sample signal and asked to compute scales 1 to 10. My CPU is an i7-3610QM.
Code used:
clear all
%% Benchmark parameters
results_file_name = 'results_scale1-10.csv';
number_of_random_runs = 10;
scales = 1:10;
number_of_random_samples = 1000000;
%% Construct a cell array containing all the wavelet names
wavelet_haar_names = {'haar'};
wavelet_db_names = {'db1'; 'db2'; 'db3'; 'db4'; 'db5'; 'db6'; 'db7'; 'db8'; 'db9'; 'db10'};
wavelet_sym_names = {'sym2'; 'sym3'; 'sym4'; 'sym5'; 'sym6'; 'sym7'; 'sym8'};
wavelet_coif_names = {'coif1'; 'coif2'; 'coif3'; 'coif4'; 'coif5'};
wavelet_bior_names = {'bior1.1'; 'bior1.3'; 'bior1.5'; 'bior2.2'; 'bior2.4'; 'bior2.6'; 'bior2.8'; 'bior3.1'; 'bior3.3'; 'bior3.5'; 'bior3.7'; 'bior3.9'; 'bior4.4'; 'bior5.5'; 'bior6.8'};
wavelet_rbior_names = {'rbio1.1'; 'rbio1.3'; 'rbio1.5'; 'rbio2.2'; 'rbio2.4'; 'rbio2.6'; 'rbio2.8'; 'rbio3.1'; 'rbio3.3'; 'rbio3.5'; 'rbio3.7'; 'rbio3.9'; 'rbio4.4'; 'rbio5.5'; 'rbio6.8'};
wavelet_meyer_names = {'meyr'};
wavelet_dmeyer_names = {'dmey'};
wavelet_gaus_names = {'gaus1'; 'gaus2'; 'gaus3'; 'gaus4'; 'gaus5'; 'gaus6'; 'gaus7'; 'gaus8'};
wavelet_mexh_names = {'mexh'};
wavelet_morl_names = {'morl'};
wavelet_cgau_names = {'cgau1'; 'cgau2'; 'cgau3'; 'cgau4'; 'cgau5'};
wavelet_shan_names = {'shan1-1.5'; 'shan1-1'; 'shan1-0.5'; 'shan1-0.1'; 'shan2-3'};
wavelet_fbsp_names = {'fbsp1-1-1.5'; 'fbsp1-1-1'; 'fbsp1-1-0.5'; 'fbsp2-1-1'; 'fbsp2-1-0.5'; 'fbsp2-1-0.1'};
wavelet_cmor_names = {'cmor1-1.5'; 'cmor1-1'; 'cmor1-0.5'; 'cmor1-1'; 'cmor1-0.5'; 'cmor1-0.1'};
% Concatenate all wavelet names into a single cell array
wavelet_categories_names = who('wavelet*names');
wavelet_names = {};
for wavelet_categories_number=1:size(wavelet_categories_names,1)
temp = wavelet_categories_names(wavelet_categories_number);
temp = eval(temp{1});
wavelet_names = vertcat(wavelet_names, temp);
end
%% Prepare data
random_signal = rand(number_of_random_runs,number_of_random_samples);
%% Run benchmarks
result_file_ID = fopen(results_file_name, 'w');
for wavelet_number = 1:size(wavelet_names,1)
wavelet_name = wavelet_names(wavelet_number,:)
% Compute wavelet on a random signal
tic
for run = 1:number_of_random_runs
cwt(random_signal(run, :),scales,wavelet_name{1});
end
run_time_random_test = toc
fprintf(result_file_ID, '%s,', wavelet_name{1})
fprintf(result_file_ID, '%d\n', run_time_random_test)
end
size(wavelet_names,1)
fclose(result_file_ID);
If you want to see the impact of the choice of the scale:
Code used:
clear all
%% Benchmark parameters
results_file_name = 'results_sym2_change_scale.csv';
number_of_random_runs = 10;
scales = 1:10;
number_of_random_samples = 10000000;
% wavelet_names = {'sym2', 'sym3'}%, 'sym4'};
output_directory = 'output';
wavelet_names = get_all_wavelet_names();
%% Prepare data
random_signal = rand(number_of_random_runs,number_of_random_samples);
%% Prepare result folder
if ~exist(output_directory, 'dir')
mkdir(output_directory);
end
%% Run benchmarks
result_file_ID = fopen(results_file_name, 'w');
for wavelet_number = 1:size(wavelet_names,1)
wavelet_name = wavelet_names{wavelet_number}
if wavelet_number > 1
fprintf(result_file_ID, '%s\n', '');
end
fprintf(result_file_ID, '%s', wavelet_name)
run_time_random_test_scales = zeros(size(scales,2),1);
for scale_number = 1:size(scales,2)
scale = scales(scale_number);
% Compute wavelet on a random signal
tic
for run = 1:number_of_random_runs
cwt(random_signal(run, :),scale,wavelet_name);
end
run_time_random_test = toc
fprintf(result_file_ID, ',%d', run_time_random_test)
run_time_random_test_scales(scale_number) = run_time_random_test;
end
figure
bar(run_time_random_test_scales)
title(['Run time on random signal for ' wavelet_name])
xlabel('Scale')
ylabel('Run time (seconds)')
save_figure( fullfile(output_directory, ['run_time_random_test_' wavelet_name]) )
close all
end
size(wavelet_names,1)
fclose(result_file_ID);
With 3 functions:
get_all_wavelet_names.m:
function [ wavelet_names ] = get_all_wavelet_names( )
%GET_ALL_WAVELET_NAMES Get a list of available wavelet functions
%% Construct a cell array containing all the wavelet names
wavelet_haar_names = {'haar'};
wavelet_db_names = {'db1'; 'db2'; 'db3'; 'db4'; 'db5'; 'db6'; 'db7'; 'db8'; 'db9'; 'db10'};
wavelet_sym_names = {'sym2'; 'sym3'; 'sym4'; 'sym5'; 'sym6'; 'sym7'; 'sym8'};
wavelet_coif_names = {'coif1'; 'coif2'; 'coif3'; 'coif4'; 'coif5'};
wavelet_bior_names = {'bior1.1'; 'bior1.3'; 'bior1.5'; 'bior2.2'; 'bior2.4'; 'bior2.6'; 'bior2.8'; 'bior3.1'; 'bior3.3'; 'bior3.5'; 'bior3.7'; 'bior3.9'; 'bior4.4'; 'bior5.5'; 'bior6.8'};
wavelet_rbior_names = {'rbio1.1'; 'rbio1.3'; 'rbio1.5'; 'rbio2.2'; 'rbio2.4'; 'rbio2.6'; 'rbio2.8'; 'rbio3.1'; 'rbio3.3'; 'rbio3.5'; 'rbio3.7'; 'rbio3.9'; 'rbio4.4'; 'rbio5.5'; 'rbio6.8'};
wavelet_meyer_names = {'meyr'};
wavelet_dmeyer_names = {'dmey'};
wavelet_gaus_names = {'gaus1'; 'gaus2'; 'gaus3'; 'gaus4'; 'gaus5'; 'gaus6'; 'gaus7'; 'gaus8'};
wavelet_mexh_names = {'mexh'};
wavelet_morl_names = {'morl'};
wavelet_cgau_names = {'cgau1'; 'cgau2'; 'cgau3'; 'cgau4'; 'cgau5'};
wavelet_shan_names = {'shan1-1.5'; 'shan1-1'; 'shan1-0.5'; 'shan1-0.1'; 'shan2-3'};
wavelet_fbsp_names = {'fbsp1-1-1.5'; 'fbsp1-1-1'; 'fbsp1-1-0.5'; 'fbsp2-1-1'; 'fbsp2-1-0.5'; 'fbsp2-1-0.1'};
wavelet_cmor_names = {'cmor1-1.5'; 'cmor1-1'; 'cmor1-0.5'; 'cmor1-1'; 'cmor1-0.5'; 'cmor1-0.1'};
% Concatenate all wavelet names into a single cell array
wavelet_categories_names = who('wavelet*names');
wavelet_names = {};
for wavelet_categories_number=1:size(wavelet_categories_names,1)
temp = wavelet_categories_names(wavelet_categories_number);
temp = eval(temp{1});
wavelet_names = vertcat(wavelet_names, temp);
end
end
save_figure.m:
function [ ] = save_figure( output_graph_filename )
% Record aa figure as PNG and fig files
% Create the folder if it doesn't exist already.
[pathstr, name, ext] = fileparts(output_graph_filename);
if ~exist(pathstr, 'dir')
mkdir(pathstr);
end
h = gcf;
set(0,'defaultAxesFontSize',18) % http://www.mathworks.com/support/solutions/en/data/1-8XOW94/index.html?solution=1-8XOW94
boldify(h);
print('-dpng','-r600', [output_graph_filename '.png']);
print(h,[output_graph_filename '.pdf'],'-dpdf','-r600')
saveas(gcf,[output_graph_filename '.fig'], 'fig')
end
and boldify.m:
function boldify(h,g)
%BOLDIFY Make lines and text bold for standard viewgraph style.
% BOLDIFY boldifies the lines and text of the current figure.
% BOLDIFY(H) applies to the graphics handle H.
%
% BOLDIFY(X,Y) specifies an X by Y inch graph of the current
% figure. If text labels have their 'UserData' data property
% set to 'slope = ...', then the 'Rotation' property is set to
% account for changes in the graph's aspect ratio. The
% default is MATLAB's default.
% S. T. Smith
% The name of this function does not represent an endorsement by the author
% of the egregious grammatical trend of verbing nouns.
if nargin < 1, h = gcf;, end
% Set (and get) the default MATLAB paper size and position
set(gcf,'PaperPosition','default');
units = get(gcf,'PaperUnits');
set(gcf,'PaperUnits','inches');
fsize = get(gcf,'PaperPosition');
fsize = fsize(3:4); % Figure size (X" x Y") on paper.
psize = get(gcf,'PaperSize');
if nargin == 2 % User specified graph size
fsize = [h,g];
h = gcf;
end
% Set the paper position of the current figure
set(gcf,'PaperPosition', ...
[(psize(1)-fsize(1))/2 (psize(2)-fsize(2))/2 fsize(1) fsize(2)]);
fsize = get(gcf,'PaperPosition');
fsize = fsize(3:4); % Graph size (X" x Y") on paper.
set(gcf,'PaperUnits',units); % Back to original
% Get the normalized axis position of the current axes
units = get(gca,'Units');
set(gca,'Units','normalized');
asize = get(gca,'Position');
asize = asize(3:4);
set(gca,'Units',units);
ha = get(h,'Children');
for i=1:length(ha)
% if get(ha(i),'Type') == 'axes'
% changed by B. A. Miller
if strcmp(get(ha(i), 'Type'), 'axes') == 1
units = get(ha(i),'Units');
set(ha(i),'Units','normalized');
asize = get(ha(i),'Position'); % Axes Position (normalized)
asize = asize(3:4);
set(ha(i),'Units',units);
[m,j] = max(asize); j = j(1);
scale = 1/(asize(j)*fsize(j)); % scale*inches -normalized units
set(ha(i),'FontWeight','Bold');
set(ha(i),'LineWidth',2);
[m,k] = min(asize); k = k(1);
if asize(k)*fsize(k) > 1/2
set(ha(i),'TickLength',[1/8 1.5*1/8]*scale); % Gives 1/8" ticks
else
set(ha(i),'TickLength',[3/32 1.5*3/32]*scale); % Gives 3/32" ticks
end
set(get(ha(i),'XLabel'),'FontSize',18); % 14-pt labels
set(get(ha(i),'XLabel'),'FontWeight','Bold');
set(get(ha(i),'XLabel'),'VerticalAlignment','top');
set(get(ha(i),'YLabel'),'FontSize',18); % 14-pt labels
set(get(ha(i),'YLabel'),'FontWeight','Bold');
%set(get(ha(i),'YLabel'),'VerticalAlignment','baseline');
set(get(ha(i),'Title'),'FontSize',18); % 16-pt titles
set(get(ha(i),'Title'),'FontWeight','Bold');
% set(get(ha(i), 'FontSize',20, 'XTick',[]));
end
hc = get(ha(i),'Children');
for j=1:length(hc)
chtype = get(hc(j),'Type');
if chtype(1:4) == 'text'
set(hc(j),'FontSize',17); % 12 pt descriptive labels
set(hc(j),'FontWeight','Bold');
ud = get(hc(j),'UserData'); % User data
if length(ud) 8
if ud(1:8) == 'slope = ' % Account for change in actual slope
slope = sscanf(ud,'slope = %g');
slope = slope*(fsize(2)/fsize(1))/(asize(2)/asize(1));
set(hc(j),'Rotation',atan(slope)/pi*180);
end
end
elseif chtype(1:4) == 'line'
set(hc(j),'LineWidth',2);
end
end
end
Bonus: correlation between all wavelets on a random signal with 1000000 samples with the first 10 scales:
Code used:
%% PRE-REQUISITE: You need to download http://www.mathworks.com/matlabcentral/fileexchange/24253-customizable-heat-maps , which gives the function heatmap()
%% Benchmark parameters
scales = 1:10;
number_of_random_samples = 1000000;
% wavelet_names = {'sym2'; 'sym3'; 'sym4'; 'sym5'; 'sym6'; 'sym7'; 'sym8'};
% wavelet_names = {'cgau1'; 'cgau2'; 'cgau3'; 'cgau4'; 'cgau5'};
wavelet_names = {'db2'; 'sym2'};
OUTPUT_FOLDER = 'output_corr';
% wavelet_names = get_all_wavelet_names(); % WARNING: you need to remove all complex wavelets, viz. cgau1, shan, fbsp and cmor, and the heatmap will be pissed to see complex values coming to her.
%% Prepare data
random_signal = rand(1,number_of_random_samples);
results = zeros(size(wavelet_names,1), number_of_random_samples);
%% Prepare result folder
if ~exist(OUTPUT_FOLDER, 'dir')
mkdir(OUTPUT_FOLDER);
end
%% Run benchmarks
for scale_number = 1:size(scales,2)
scale = scales(scale_number);
for wavelet_number = 1:size(wavelet_names,1)
wavelet_name = wavelet_names{wavelet_number}
% Compute wavelet on a random signal
run = 1;
results(wavelet_number, :) = cwt(random_signal(run, :),scale,wavelet_name);
if wavelet_number == 999
break
end
end
correlation_results = corrcoef(results')
heatmap(correlation_results, [], [], '%0.2f', 'MinColorValue', -1.0, 'MaxColorValue', 1.0, 'Colormap', 'jet',...
'Colorbar', true, 'ColorLevels', 64, 'UseFigureColormap', false);
title(['Correlation matrix for scale ' num2str(scale)]);
xlabel(['Wavelet 1 to ' num2str(size(wavelet_names,1)) ' for scale ' num2str(scale)]);
ylabel(['Wavelet 1 to ' num2str(size(wavelet_names,1)) ' for scale ' num2str(scale)]);
snapnow
print('-dpng','-r600',fullfile(OUTPUT_FOLDER, ['scalecorr' num2str(scale) '.png']))
end
Correlation for each wavelet between different scales (1 to 100):
Code used:
%% PRE-REQUISITE: You need to download http://www.mathworks.com/matlabcentral/fileexchange/24253-customizable-heat-maps , which gives the function heatmap()
%% Benchmark parameters
scales = 1:100;
number_of_random_samples = 1000000;
% wavelet_name = 'gaus2';
% wavelet_names = {'sym2', 'sym3'}%, 'sym4'};
OUTPUT_FOLDER = 'output_corr';
wavelet_names = get_all_wavelet_names(); % WARNING: you need to remove all complex wavelets, viz. cgau1, shan, fbsp and cmor, and the heatmap will be pissed to see complex values coming to her.
%% Prepare data
random_signal = rand(1,number_of_random_samples);
results = zeros(size(scales,2), number_of_random_samples);
%% Prepare result folder
if ~exist(OUTPUT_FOLDER, 'dir')
mkdir(OUTPUT_FOLDER);
end
%% Run benchmarks
for wavelet_number = 1:size(wavelet_names,1)
wavelet_name = wavelet_names{wavelet_number}
run_time_random_test_scales = zeros(size(scales,2),1);
for scale_number = 1:size(scales,2)
scale = scales(scale_number);
run = 1;
% Compute wavelet on a random signal
results(scale_number, :) = cwt(random_signal(run, :),scale,wavelet_name);
end
correlation_results = corrcoef(results')
heatmap(correlation_results, [], [], '%0.2f', 'MinColorValue', -1.0, 'MaxColorValue', 1.0, 'Colormap', 'jet',...
'Colorbar', true, 'ColorLevels', 64, 'UseFigureColormap', false);
title(['Correlation matrix for wavelet ' wavelet_name]);
xlabel(['Scales 1 to ' num2str(max(scales)) ' for wavelet ' wavelet_name]);
ylabel(['Scales 1 to ' num2str(max(scales)) ' for wavelet ' wavelet_name]);
snapnow
print('-dpng','-r600',fullfile(OUTPUT_FOLDER, [wavelet_name '_scalecorr_scale1to' num2str(max(scales)) '.png']))
end

spiral meshgrid in matlab

I'm trying to produce some computer generated holograms by using MATLAB. I used equally spaced mesh grid to initialize the spatial grid, and I got the following image
This pattern is sort of what I need except the center region. The fringe should be sharp but blurred. I think it might be the problem of the mesh grid. I tried generate a grid in polar coordinates and the map it into Cartesian coordinates by using MATLAB's pol2cart function. Unfortunately, it doesn't work as well. One may suggest that using fine grids. It doesn't work too. I think if I can generate a spiral mesh grid, perhaps the problem is solvable. In addition, the number of the spiral arms could, in general, be arbitrary, could anyone give me a hint on this?
I've attached the code (My final projects are not exactly the same, but it has a similar problem).
clc; clear all; close all;
%% initialization
tic
lambda = 1.55e-6;
k0 = 2*pi/lambda;
c0 = 3e8;
eta0 = 377;
scale = 0.25e-6;
NELEMENTS = 1600;
GoldenRatio = (1+sqrt(5))/2;
g = 2*pi*(1-1/GoldenRatio);
pntsrc = zeros(NELEMENTS, 3);
phisrc = zeros(NELEMENTS, 1);
for idxe = 1:NELEMENTS
pntsrc(idxe, :) = scale*sqrt(idxe)*[cos(idxe*g), sin(idxe*g), 0];
phisrc(idxe) = angle(-sin(idxe*g)+1i*cos(idxe*g));
end
phisrc = 3*phisrc/2; % 3 arms (topological charge ell=3)
%% post processing
sigma = 1;
polfilter = [0, 0, 1i*sigma; 0, 0, -1; -1i*sigma, 1, 0]; % cp filter
xboundl = -100e-6; xboundu = 100e-6;
yboundl = -100e-6; yboundu = 100e-6;
xf = linspace(xboundl, xboundu, 100);
yf = linspace(yboundl, yboundu, 100);
zf = -400e-6;
[pntobsx, pntobsy] = meshgrid(xf, yf);
% how to generate a right mesh grid such that we can generate a decent result?
pntobs = [pntobsx(:), pntobsy(:), zf*ones(size(pntobsx(:)))];
% arbitrary mesh may result in "wrong" results
NPNTOBS = size(pntobs, 1);
nxp = length(xf);
nyp = length(yf);
%% observation
Eobs = zeros(NPNTOBS, 3);
matlabpool open local 12
parfor nobs = 1:NPNTOBS
rp = pntobs(nobs, :);
Erad = [0; 0; 0];
for idx = 1:NELEMENTS
rs = pntsrc(idx, :);
p = exp(sigma*1i*2*phisrc(idx))*[1 -sigma*1i 0]/2; % simplified here
u = rp - rs;
r = sqrt(u(1)^2+u(2)^2+u(3)^2); %norm(u);
u = u/r; % unit vector
ut = [u(2)*p(3)-u(3)*p(2),...
u(3)*p(1)-u(1)*p(3), ...
u(1)*p(2)-u(2)*p(1)]; % cross product: u cross p
Erad = Erad + ... % u cross p cross u, do not use the built-in func
c0*k0^2/4/pi*exp(1i*k0*r)/r*eta0*...
[ut(2)*u(3)-ut(3)*u(2);...
ut(3)*u(1)-ut(1)*u(3); ...
ut(1)*u(2)-ut(2)*u(1)];
end
Eobs(nobs, :) = Erad; % filter neglected here
end
matlabpool close
Eobs = Eobs/max(max(sum(abs(Eobs), 2))); % normailized
%% source, gaussian beam
E0 = 1;
w0 = 80e-6;
theta = 0; % may be titled
RotateX = [1, 0, 0; ...
0, cosd(theta), -sind(theta); ...
0, sind(theta), cosd(theta)];
Esrc = zeros(NPNTOBS, 3);
for nobs = 1:NPNTOBS
rp = RotateX*[pntobs(nobs, 1:2).'; 0];
z = rp(3);
r = sqrt(sum(abs(rp(1:2)).^2));
zR = pi*w0^2/lambda;
wz = w0*sqrt(1+z^2/zR^2);
Rz = z^2+zR^2;
zetaz = atan(z/zR);
gaussian = E0*w0/wz*exp(-r^2/wz^2-1i*k0*z-1i*k0*0*r^2/Rz/2+1i*zetaz);% ...
Esrc(nobs, :) = (polfilter*gaussian*[1; -1i; 0]).'/sqrt(2)/2;
end
Esrc = [Esrc(:, 2), Esrc(:, 3), Esrc(:, 1)];
Esrc = Esrc/max(max(sum(abs(Esrc), 2))); % normailized
toc
%% visualization
fringe = Eobs + Esrc; % I'll have a different formula in my code
normEsrc = reshape(sum(abs(Esrc).^2, 2), [nyp nxp]);
normEobs = reshape(sum(abs(Eobs).^2, 2), [nyp nxp]);
normFringe = reshape(sum(abs(fringe).^2, 2), [nyp nxp]);
close all;
xf0 = linspace(xboundl, xboundu, 500);
yf0 = linspace(yboundl, yboundu, 500);
[xfi, yfi] = meshgrid(xf0, yf0);
data = interp2(xf, yf, normFringe, xfi, yfi);
figure; surf(xfi, yfi, data,'edgecolor','none');
% tri = delaunay(xfi, yfi); trisurf(tri, xfi, yfi, data, 'edgecolor','none');
xlim([xboundl, xboundu])
ylim([yboundl, yboundu])
% colorbar
view(0,90)
colormap(hot)
axis equal
axis off
title('fringe thereo. ', ...
'fontsize', 18)
I didn't read your code because it is too long to do such a simple thing. I wrote mine and here is the result:
the code is
%spiral.m
function val = spiral(x,y)
r = sqrt( x*x + y*y);
a = atan2(y,x)*2+r;
x = r*cos(a);
y = r*sin(a);
val = exp(-x*x*y*y);
val = 1/(1+exp(-1000*(val)));
endfunction
%show.m
n=300;
l = 7;
A = zeros(n);
for i=1:n
for j=1:n
A(i,j) = spiral( 2*(i/n-0.5)*l,2*(j/n-0.5)*l);
end
end
imshow(A) %don't know if imshow is in matlab. I used octave.
the key for the sharpnes is line
val = 1/(1+exp(-1000*(val)));
It is logistic function. The number 1000 defines how sharp your image will be. So lower it for more blurry image or higher it for sharper.
I hope this answers your question ;)
Edit: It is real fun to play with. Here is another spiral:
function val = spiral(x,y)
s= 0.5;
r = sqrt( x*x + y*y);
a = atan2(y,x)*2+r*r*r;
x = r*cos(a);
y = r*sin(a);
val = 0;
if (abs(x)<s )
val = s-abs(x);
endif
if(abs(y)<s)
val =max(s-abs(y),val);
endif
%val = 1/(1+exp(-1*(val)));
endfunction
Edit2: Fun, fun, fun! Here the arms do not get thinner.
function val = spiral(x,y)
s= 0.1;
r = sqrt( x*x + y*y);
a = atan2(y,x)*2+r*r; % h
x = r*cos(a);
y = r*sin(a);
val = 0;
s = s*exp(r);
if (abs(x)<s )
val = s-abs(x);
endif
if(abs(y)<s)
val =max(s-abs(y),val);
endif
val = val/s;
val = 1/(1+exp(-10*(val)));
endfunction
Damn your question I really need to study for my exam, arghhh!
Edit3:
I vectorised the code and it runs much faster.
%spiral.m
function val = spiral(x,y)
s= 2;
r = sqrt( x.*x + y.*y);
a = atan2(y,x)*8+exp(r);
x = r.*cos(a);
y = r.*sin(a);
val = 0;
s = s.*exp(-0.1*r);
val = r;
val = (abs(x)<s ).*(s-abs(x));
val = val./s;
% val = 1./(1.+exp(-1*(val)));
endfunction
%show.m
n=1000;
l = 3;
A = zeros(n);
[X,Y] = meshgrid(-l:2*l/n:l);
A = spiral(X,Y);
imshow(A)
Sorry, can't post figures. But this might help. I wrote it for experiments with amplitude spatial modulators...
R=70; % radius of curvature of fresnel lens (in pixel units)
A=0; % oblique incidence by linear grating (1=oblique 0=collinear)
B=1; % expanding by fresnel lens (1=yes 0=no)
L=7; % topological charge
Lambda=30; % linear grating fringe spacing (in pixels)
aspect=1/2; % fraction of fringe period that is white/clear
xsize=1024; % resolution (xres x yres number data pts calculated)
ysize=768; %
% define the X and Y ranges (defined to skip zero)
xvec = linspace(-xsize/2, xsize/2, xsize); % list of x values
yvec = linspace(-ysize/2, ysize/2, ysize); % list of y values
% define the meshes - matrices linear in one dimension
[xmesh, ymesh] = meshgrid(xvec, yvec);
% calculate the individual phase components
vortexPh = atan2(ymesh,xmesh); % the vortex phase
linPh = -2*pi*ymesh; % a phase of linear grating
radialPh = (xmesh.^2+ymesh.^2); % a phase of defocus
% combine the phases with appropriate scales (phases are additive)
% the 'pi' at the end causes inversion of the pattern
Ph = L*vortexPh + A*linPh/Lambda + B*radialPh/R^2;
% transmittance function (the real part of exp(I*Ph))
T = cos(Ph);
% the binary version
binT = T > cos(pi*aspect);
% plot the pattern
% imagesc(binT)
imagesc(T)
colormap(gray)