How to sample a signal using Golomb Ruler? - matlab

I'm trying to sample a multi-sine signal by Golomb Ruler of length 151, how can I achieve this ?
Below is the signal plot for a sine wave sampled by Golomb Ruler of length 151.
Amplitude spectrum of the above samples (visible peak at the
expected frequency 24Hz above the “under-sampling” noise)
clear all
close all
clc
%%
Fs = 1000; % Sampling Freq.
T = 1/Fs; % Sampling period
L = 1024; % Length of signal
t = 2*(0:L-1)*T; % Time vector
x = 0; % Signal intial value
y = 0; % Signal intial value
F = 24; % Signal Freq.
seq = [0 4 20 30 57 59 62 76 100 111 123 136 144 145 151]; %Golomb Seq. ??
% x = cos(2*pi*F*seq);
for i01=1:length(seq)
for u = 0:seq(i01)
x = x + cos(2*pi*F*u+pi/2);
end
end
figure
subplot(2,2,1)
plot(seq,x)
title('Original signal')

Related

Issue Band Pass Filtering Matlab

I'm trying to bandpass filter the signal between 10 to 450Hz, but something keeps making the output weird. The when the lower cutoff is 30, it still works as expected, but if it gets to 20 or below it get's wonky.
Why is this happening?
Fs = 1000;
t = 0:1/Fs:1;
x = [2 10 20 15 2]*sin(2*pi*[5 60 150 250 550]'.*t) + randn(size(t))/10;
Y = fft(x);
L = length(x);
P2 = abs(Y/L);
P1 = P2(1:L/2+1);
P1(2:end-1) = 2*P1(2:end-1);
f = Fs*(0:(L/2))/L;
x = abs(x);
bandpass(x,[30 450],Fs)
30 Hz cutoff
20 Hz cutoff

Radar plot Area Fill - Matlab

This is a radar plot script for MATLAB I copied from Google Search. I was hoping to use radar plot with different scales with 4 or 5 axes.
How would I fill the graph of this radar plot? Should I use patch or fill? I know this shouldn't take a long time to do this. My math isn't that great.
Thanks in advance,
Gary
function [f, ca, o] = spider(data,tle,rng,lbl,leg,f)
% create a spider plot for ranking the data
% function [f, ca, o] = spider(data,tle,rng,lbl,leg,f)
%
% inputs 6 - 5 optional
% data input data (NxM) (# axes (M) x # data sets (N)) class real
% tle spider plot title class char
% rng peak range of the data (Mx1 or Mx2) class real
% lbl cell vector axes names (Mxq) in [name unit] pairs class cell
% leg data set legend identification (1xN) class cell
% f figure handle or plot handle class real
%
% outptus 3 - 3 optional
% f figure handle class integer
% x axes handle class real
% o series object handles class real
%
% michael arant - jan 30, 2008
%
% to skip any parameter, enter null []
%
% examples
%
% spider([1 2 3; 4 5 6; 7 8 9; 10 11 12; 13 14 15;16 17 18; ...
% 19 20 21; 22 23 24; 25 26 27]','test plot');
%
% spider([1 2 3 4; 4 5 6 7; 7 8 9 10; 10 11 12 13; 13 14 15 16; ...
% 16 17 18 19; 19 20 21 22; 22 23 24 25; 25 26 27 28],'test plot', ...
% [[0:3:24]' [5:3:29]'],[],{'Case 1' 'Case 2' 'Case 3' 'Case 4'});
%
% spider([1 2 3 4; 4 5 6 7; 7 8 9 10; 10 11 12 13; 13 14 15 16; ...
% 16 17 18 19; 19 20 21 22; 22 23 24 25; 25 26 27 28],'test plot', ...
% [],[],{'Case 1' 'Case 2' 'Case 3' 'Case 4'});
%
% figure; clf; set(gcf,'color','w'); s = zeros(1,4);
% for ii = 1:4; s(ii) = subplot(2,2,ii); end
%
% spider([1 2 3; 4 5 6; 7 8 9; 10 11 12; 13 14 15;16 17 18; ...
% 19 20 21; 22 23 24; 25 26 27]','test plot 1',[],[],[],s(1));
%
% spider([1 2 3; 4 5 6; 7 8 9; 10 11 12; 13 14 15;16 17 18; ...
% 19 20 21; 22 23 24; 25 26 27],'test plot 2',[0 30],[],[],s(2));
%
% spider([1 2 3 4; 4 5 6 7; 7 8 9 10; 10 11 12 13; 13 14 15 16; ...
% 16 17 18 19; 19 20 21 22; 22 23 24 25; 25 26 27 28]','test plot 3', ...
% [0 30],{'Label 1' 'Unit 1'; 'Label 2' 'Unit 2'; 'Label 3' 'Unit 3'; ...
% 'Label 4' 'Unit 4'},{'Case 1' 'Case 2' 'Case 3' 'Case 4' 'Case 5' ...
% 'Case 6' 'Case 7' 'Case 8' 'Case 9'},s(3));
%
% spider([1 2 3 4; 4 5 6 7; 7 8 9 10; 10 11 12 13; 13 14 15 16; ...
% 16 17 18 19; 19 20 21 22; 22 23 24 25; 25 26 27 28],'test plot 4', ...
% [[0:3:24]' [5:3:29]'],[],{'Case 1' 'Case 2' 'Case 3' 'Case 4'},s(4));
% data check
if nargin < 1; help spider; error('Need data to plot'); end
% size segments and number of cases
[r c] = size(data);
% exit for too few axes
if r < 3
errordlg('Must have at least three measuremnt axes')
error('Program Termination: Must have a minimum of three axes')
end
% title
if ~exist('tle','var') || isempty(tle) || ~ischar(tle)
tle = 'Spider Plot';
end
% check for maximum range
if ~exist('rng','var') || isempty(rng) || ~isreal(rng)
% no range given or range is in improper format
% define new range
rng = [min([min(data,[],2) zeros(r,1)],[],2) max(data,[],2)];
% check for negative minimum values
if ~isempty(ismember(-1,sign(data)))
% negative value found - adjust minimum range
for ii = 1:r
% negative range for axis ii - set new minimum
if min(data(ii,:)) < 0
rng(ii,1) = min(data(ii,:)) - ...
0.25 * (max(data(ii,:)) - min(data(ii,:)));
end
end
end
elseif size(rng,1) ~= r
if size(rng,1) == 1
% assume that all axes have commom scale
rng = ones(r,1) * rng;
else
% insuffent range definition
uiwait(msgbox(char('Range size must be Mx1 - number of axes x 1', ...
sprintf('%g axis ranges defined, %g axes exist',size(rng,1),r))))
error(sprintf('%g axis ranges defined, %g axes exist',size(rng,1),r))
end
elseif size(rng,2) == 1
% assume range is a maximum range - define minimum
rng = sort([min([zeros(r,1) min(data,[],2) - ...
0.25 * (max(data,[],2) - min(data,[],2))],[],2) rng],2);
end
% check for axis labels
if ~exist('lbl','var') || isempty(lbl)
% no labels given - define a default lable
lbl = cell(r,1); for ii = 1:r; lbl(ii) = cellstr(sprintf('Axis %g',ii)); end
elseif size(lbl,1) ~= r
if size(lbl,2) == r
lbl = lbl';
else
uiwait(msgbox(char('Axis labels must be Mx1 - number of axes x 1', ...
sprintf('%g axis labels defined, %g axes exist',size(lbl,1),r))))
error(sprintf('%g axis labels defined, %g axes exist',size(lbl,1),r))
end
elseif ischar(lbl)
% check for charater labels
lbl = cellstr(lbl);
end
if ~exist('leg','var') || isempty(leg)
% no data legend - define default legend
leg = cell(1,c); for ii = 1:c; leg(ii) = cellstr(sprintf('Set %g',ii)); end
elseif numel(leg) ~= c
uiwait(msgbox(char('Data set label must be 1XN - 1 x number of sets', ...
sprintf('%g data sets labeled, %g exist',numel(leg),c))))
error(sprintf('%g data sets labeled, %g exist',numel(leg),c))
end
% check for figure or axes
if ~exist('f','var')
% no figure or axes requested - generate new ones
f = figure; ca = gca(f); cla(ca); hold on; set(f,'color','w')
elseif ismember(f,get(0,'children')')
% existing figure - clear and set up
ca = gca(f); hold on;
elseif isint(f)
% generating a new figure
figure(f); ca = gca(f); cla(ca); hold on
else
% may be an axes - may be garbage
try
%is this an axes?
if ismember(get(f,'parent'),get(0,'children')')
% existing figure axes - use
ca = f; f = get(f,'parent'); hold on
end
catch
% make new figure and axes
disp(sprintf('Invalid axes handle %g passed. Generating new figure',f))
f = figure; ca = gca(f); cla(ca); hold on
end
end
% set the axes to the current text axes
axes(ca)
% set to add plot
set(ca,'nextplot','add');
% clear figure and set limits
set(ca,'visible','off'); set(f,'color','w')
set(ca,'xlim',[-1.25 1.25],'ylim',[-1.25 1.25]); axis(ca,'equal','manual')
% title
text(0,1.3,tle,'horizontalalignment','center','fontweight','bold');
% define data case colors
col = color_index(c);
% scale by range
angw = linspace(0,2*pi,r+1)';
mag = (data - rng(:,1) * ones(1,c)) ./ (diff(rng,[],2) * ones(1,c));
% scale trimming
mag(mag < 0) = 0; mag(mag > 1) = 1;
% wrap data (close the last axis to the first)
ang = angw(1:end-1); angwv = angw * ones(1,c); magw = [mag; mag(1,:)];
% make the plot
% define the axis locations
start = [zeros(1,r); cos(ang')]; stop = [zeros(1,r); sin(ang')];
% plot the axes
plot(ca,start,stop,'color','k','linestyle','-'); axis equal
% plot axes markers
inc = 0.25:.25:1; mk = .025 * ones(1,4); tx = 4 * mk; tl = 0:.25:1;
% loop each axis ang plot the line markers and labels
% add axes
for ii = 1:r
% plot tick marks
tm = plot(ca,[[cos(ang(ii)) * inc + sin(ang(ii)) * mk]; ...
[cos(ang(ii)) * inc - sin(ang(ii)) * mk]], ...
[[sin(ang(ii)) * inc - cos(ang(ii)) * mk] ;
[sin(ang(ii)) * inc + cos(ang(ii)) * mk]],'color','k');
% label the tick marks
for jj = 1:4
% temp = text([cos(ang(ii)) * inc(jj) + sin(ang(ii)) * tx(jj)], ...
% [sin(ang(ii)) * inc(jj) - cos(ang(ii)) * tx(jj)], ...
% num2str(chop(rng(ii,1) + inc(jj)*diff(rng(ii,:)),2)), ...
% 'fontsize',8);
temp = text([cos(ang(ii)) * inc(jj) + sin(ang(ii)) * tx(jj)], ...
[sin(ang(ii)) * inc(jj) - cos(ang(ii)) * tx(jj)], ...
num2str(rd(rng(ii,1) + inc(jj)*diff(rng(ii,:)),-2)), ...
'fontsize',8);
% flip the text alignment for lower axes
if ang(ii) >= pi
set(temp,'HorizontalAlignment','right')
end
end
% label each axis
temp = text([cos(ang(ii)) * 1.1 + sin(ang(ii)) * 0], ...
[sin(ang(ii)) * 1.1 - cos(ang(ii)) * 0], ...
char(lbl(ii,:)));
% flip the text alignment for right side axes
if ang(ii) > pi/2 && ang(ii) < 3*pi/2
set(temp,'HorizontalAlignment','right')
end
end
% plot the data
o = polar(ca,angw*ones(1,c),magw);
% set color of the lines
for ii = 1:c; set(o(ii),'color',col(ii,:),'linewidth',1.5); end
% apply the legend
temp = legend(o,leg,'location','best');
return
function [v] = rd(v,dec)
% quick round function (to specified decimal)
% function [v] = rd(v,dec)
%
% inputs 2 - 1 optional
% v number to round class real
% dec decimal loaction class integer
%
% outputs 1
% v result class real
%
% positive dec shifts rounding location to the right (larger number)
% negative dec shifts rounding location to the left (smaller number)
%
% michael arant
% Michelin Maericas Research and Development Corp
if nargin < 1; help rd; error('I/O error'); end
if nargin == 1; dec = 0; end
v = v / 10^dec;
v = round(v);
v = v * 10^dec;
function [val] = color_index(len)
% get unique colors for each item to plot
% function [val] = color_index(len)
%
% inputs 1
% len number of objects class integer
%
% outputs 1
% val color vector class real
%
% michael arant
if nargin < 1 || nargout < 1; help color_index; error('I / O error'); end
if len == 1
val = [0 0 0];
else
% initial color posibilities (no white)
% default color scale
col = [ 0 0 0
0 0 1
0 1 1
0 1 0
1 1 0
1 0 1
1 0 0];
% reduce if fewer than 6 items are needed (no interpolation needed)
switch len
case 1, col([2 3 4 5 6 7],:) = [];
case 2, col([2 3 4 5 6],:) = [];
case 3, col([3 4 5 6],:) = [];
case 4, col([3 5 6],:) = [];
case 5, col([5 6],:) = [];
case 6, col(6,:) = [];
end
% number of requested colors
val = zeros(len,3); val(:,3) = linspace(0,1,len)';
% interpolate to fill in colors
val(:,1) = interp1q(linspace(0,1,size(col,1))',col(:,1),val(:,3));
val(:,2) = interp1q(linspace(0,1,size(col,1))',col(:,2),val(:,3));
val(:,3) = interp1q(linspace(0,1,size(col,1))',col(:,3),val(:,3));
end
function [res] = isint(val)
% determines if value is an integer
% function [res] = isint(val)
%
% inputs 1
% val value to be checked class real
%
% outputs 1
% res result (1 is integer, 0 is not) class integer
%
% michael arant may 15, 2004
if nargin < 1; help isint; error('I / O error'); end
% numeric?
if ~isnumeric(val); error('Must be numeric'); end
% check for real number
if isreal(val) & isnumeric(val)
% check for integer
if round(val) == val
res = 1;
else
res = 0;
end
else
res = 0;
end

Matlab: Extracting error values from a fit

I am using the following code to import a spreadsheet with two coloumns x = intensity and y = angle and to get the Gaussian curve fitting:
%% Initialize variables
filename = ['E:\XRD\Enamel\MPS\3PC\Chiplots (starting from 0)\MPS_3Pcontrol_map_' j '.dat'];
startRow = 5;
%% Format string for each line of text:
formatSpec = '%14f%f%[^\n\r]';
%% Open the text file.
fileID = fopen(filename,'r');
%% Read columns of data according to format string.
dataArray = textscan(fileID, formatSpec, 'Delimiter', '', 'WhiteSpace', '', 'HeaderLines' ,startRow-1, 'ReturnOnError', false);
%% Close the text file.
fclose(fileID);
%% Allocate imported array to column variable names
plots.angle = dataArray{:, 1};
plots.intensity = dataArray{:, 2};
%% Fit: 'Gauss'.
[xData, yData] = prepareCurveData(plots.(['angle' num2str(j)]), plots.(['intensity' num2str(j)]));
% Set up fittype and options.
ft = fittype( 'y0+a*exp(-((x-xa)/wa)^2) + b*exp(-((x-xb)/wb)^2) + c*exp(-((x-xc)/wc)^2) + d*exp(-((x-xd)/wd)^2) + e*exp(-((x-xe)/we)^2) + f*exp(-((x-xf)/wf)^2)', 'independent', 'x', 'dependent', 'y' );
opts = fitoptions( 'Method', 'NonlinearLeastSquares' );
opts.Display = 'Off';
opts.Lower = [0 0 0 0 0 0 0.1 0.1 0.1 0.1 0.1 0.1 -Inf -Inf -Inf -Inf -Inf -Inf -Inf];
opts.StartPoint = [1400 1400 1000 1200 1200 1000 25 25 25 25 25 25 75 125 170 250 275 325 0.5];
opts.Upper = [inf inf inf inf inf inf 50 50 50 50 50 50 inf inf inf inf inf inf Inf];
% Fit model to data.
[fitresult, gof] = fit( xData, yData, ft, opts );
I can get the values of the coefficients using: cfit(fitresult) to get the following:
From the above I can extract the coefficients values using coeffvalues(cfit(fitresult)):
The problem is I cant get the values highlighted in yellow, which I need to calculate the standard error using the equation (standard error = standard deviation/square root of n)
Can I extract the values highlighted in yellow in order to calculate the standard error?
You need to use the confint function. This will give you the 95% confidence bounds for the fit. It works like this:
confint(cfit(fitresult))
If you want your own confidence interval, you can set it like this:
confint(cfit(fitresult,[insert confidence interval here (such as 0.85)]))
That should do what you are looking for.

Matlab: normalized cut implementation

I have implemented "normalized cut" segmentation. The change here is that, instead of giving an image as input, I have given an matrix of image. As my output looks odd to me. I need to know whether my implementation is correct or not.
Code:
clear all
tic;
% im = imread('lena.pgm');
im =[94 122 99 101 111 101;
99 92 103 87 107 116;
93 109 113 84 86 106;
5 17 6 54 56 53;
13 11 5 56 44 50;
0 10 5 49 42 51];
% resizing to avoid out of memory error
% cim=imresize(im,[100 100]);
cim=im;
[r, c]=size(cim);
ind=find(cim);
lind=length(ind);
[I,J]=ind2sub([r,c],ind);
% % I've used linear indexing to speed up the partitioning
% vectoring the pixel nodes
for i=1:lind
V1(i)=double(cim(ind(i)));
end
% normalizing to [0-1] scale
V=(V1./255);
% w is the weight matrix (similarity matrix or adjacency matrix)
w=zeros(lind,lind);
% r, sigmaI, sigmaX values
rad=4.5;
sigi=10;
sigx=25;
% computing the weight matrix
for i=1:lind
x1=I(i,1);
y1=J(i,1);
for j=1:lind
if (i==j)
w(i,j)=1;
else
x2=I(j,1);
y2=J(j,1);
dist=((x1-x2)^2 + (y1-y2)^2);
if sqrt(dist)>=rad
dx=0;
else
dx=exp(-((dist)/(sigx^2)));
end
pdiff=(V(i)-V(j))^2;
di=exp(-((pdiff)/(sigi)^2));
w(i,j)=di*dx;
end
end
end
d=zeros(lind,lind);
s=sum(w,2);
% the diagonal matrix for computing the laplacian matrix
for i=1:lind
d(i,i)=s(i);
end
A=zeros(lind,lind);
A=(d-w); % A is the laplacian matrix
% vt has the eigen vectors corresponding to eigen values in vl
% other eigs / eig functions in matlab can be used but I'm using the
% function to compute the 5 smallest eigenvectors
[vt,vl]=eigs(A,d,5,'sm');
% se has the second smallest eigen vector, third and so on
se=vt(:,2:4);
% % % % % Simultaneous 'k' partitions
k=6;
id=kmeans(se,k);
imp=cell(1,k);
pic=cell(1,k);
for i=1:k
imp{1,i}= find(id(:,1)==i);
mat=zeros(100,100);
in=imp{1,i};
mat(in)=cim(in);
pic{1,i}=uint8(mat);
% figure,imshow(pic{1,i});
end
% pic has the sub graphs or partitiond sub images
figure;
subplot(2,4,1);imshow(uint8(im));title('Original image');
subplot(2,4,2);imshow(uint8(cim));title('Preprocessed image');
subplot(2,4,3);imshow(pic{1,1});title('Partition 1');
subplot(2,4,4);imshow(pic{1,2});title('Partition 2');
subplot(2,4,5);imshow(pic{1,3});title('Partition 3');
subplot(2,4,6);imshow(pic{1,4});title('Partition 4');
subplot(2,4,7);imshow(pic{1,5});title('Partition 5');
subplot(2,4,8);imshow(pic{1,6});title('Partition 6');
toc;
Output:
Thanks in advance.

Plot heat conduction temperature at various radii with Matlab

I have an array in Matlab that is updated for every time step: each row corresponds to a time and each column represents a temperature at a certain radius from the center. It would also be handy if a color gradient could be applied to the plot using the meshgrid and contourf commands. So far, this is the Matlab code that I have, but I am not sure how to get the temperature into the plot and animate the change in temperature.
Tinf = 200; % ambient temperature
% where r1 = radius1, r2 = radius2, etc.
% t = time
% rows = time
% columns = radius
% r1 r2 r3 r4 r5
T = [98 105 110 118 128; % t=1
109 110 117 124 134; % t=2
110 118 120 130 144]; % t=3
r = 0.08; % radius of circle
rx = -r:0.01:r;
ry = r:-0.01:-r;
[x_coor, y_coor] = meshgrid(rx, ry);
radius = sqrt(x_coor.^2+y_coor.^2);
figure(1)
contourf(radius,'edgecolor','none')
I am trying to create a circular plot in Matlab that would show the temperature (color) at each radius and animate that temperature (change color) as it increases or decreases with time.
An example of such a plot at a certain time would be:
So column 1 in the T array corresponds to node 1 in the picture, column 2 corresponds to node 2, etc. Thus at time = 0 then node1 = 98, node2 = 105, node3 = 110, node4 = 118, node5 = 128; at time = 1 then node1 = 109, node2 = 110, node3 = 117, node4 = 124, node5 = 134; and so on.
Any suggestions to accomplish such a plot would be very helpful.
Same as #Magla's nice answer but draws a single surface (not an overlay) allowing interpolation
T = [98 105 110 118 128;
109 110 117 124 134;
114 118 120 130 138];
Rmax = 30;
[x,y,z] = sphere(100);
x=x*Rmax;
y=y*Rmax;
rxy2 = x.^2+y.^2;
r = [0 10 20 30];
r2 = r.^2;
figure('Color', 'w');
for ind_t = 1:size(T,1)
for ii = 1:length(r2)-1
ir_find = find(rxy2<=r2(ii+1) & rxy2>r2(ii));
z(ir_find) = T(ind_t,ii);
end
hax = axes('Position',[0 0 1 1]);
h = surf(x,y,z) % sphere centered at origin
shading interp
set(h, 'EdgeColor', 'None');
view(0,90);
axis equal;
set(hax, 'Visible', 'Off', 'CLim', [min(T(:)) max(T(:))]);
pause(0.5);
end
edit
Rewrote to use meshgrid and to use the particular radii etc of interest. Make sure to adjust r_res to a value you find adequate.
T = [98 105 110 118 128;
109 110 117 124 134;
114 118 120 130 138];
%---------------------------------------
r = 0.08; % radius of circle
r_res = 0.0005;
rx = -r:r_res:r;
ry = rx;
[x, y] = meshgrid(rx, ry);
rxy2 = x.^2+y.^2;
z=ones(size(rxy2))*NaN;
%---------------------------------------
Nshells = size(T,2);
r = [0:1/Nshells:1]*r;
r2 = r.^2;
figure('Color', 'w');
colormap hot
for ind_t = 1:size(T,1)
for ii = 1:Nshells
ir_find = find(rxy2<=r2(ii+1) & rxy2>r2(ii));
z(ir_find) = T(ind_t,ii);
end
hax = axes('Position',[0 0 1 1]);
h = surf(x,y,z) % sphere centered at origin
shading interp
set(h, 'EdgeColor', 'None');
view(0,90);
axis equal;
set(hax, 'Visible', 'Off', 'CLim', [min(T(:)) max(T(:))]);
pause(0.5);
end
Here is a solution that makes use of sphere. sphere generates the matrices x and y that are multiply by a decreasing radius r, and matrix z that is reduced to a single value (a sphere becomes a disk). z is multiplied by the temperature and disks are plotted on top of each other. Colors depend on the min and max of the whole input matrix. Animation is done with pause.
T = [98 105 110 118 128;
109 110 117 124 134;
114 118 120 130 138];
[x,y,z] = sphere(100);
r = [50 40 30 20 10];
figure('Color', 'w');
for ind_t = 1:size(T,1)
hax = axes('Position',[0 0 1 1]);
for ii = 1:length(r)
h = surf(x*r(ii),y*r(ii),z*0+T(ind_t,ii)) % sphere centered at origin
set(h, 'EdgeColor', 'None');
hold on;
end
view(0,90);
axis equal;
set(hax, 'Visible', 'Off', 'CLim', [min(T(:)) max(T(:))]);
pause(0.5);
end
This gives