matlab, plotting 2 vecctors as a list, how can I give them different line types and colours using this syntax - matlab

I have checked SO and ML help but cannot see a solution to this.
using this syntax
E = 10; % amplitude
sample_1_hz = 1000;
sample_2_hz = 11000;
fs = 10000; % sample rate in Hz
Samples = 100;
time_scale = (0:Samples-1)'/fs;
sig_1 = E*sin(2*pi*time_scale*sample_1_hz);
sig_2 = E*sin(2*pi*time_scale*sample_2_hz);
plot(time_scale,[sig_1 sig_2]);
grid('on');
xlabel('Time');
ylabel('Amplitude');
legend('1000 Hz', '11000 Hz');
how can I alter the lines to have different line styles and colors?

the two lines coincide in every point in time_scale in the example code you posted (plot their difference sig_1-sig_2 and see the values in the 1e-13), so the only way to see both of them is to make one "dashed" and the other "solid" so you can see one on top of the other , or add a marker to one of them. for example,
plot(time_scale, sig_1 ,'-',time_scale,sig_2,':o','LineWidth',2 );

Related

How to detect multiple instances of symbols in image using matlab

I have tried to use the code provided in this answer to detect symbols using template matching with the FFT (via fft2)
However, the code only detects one symbol but it doesn't detect all similar symbols.
The code has been adapted from the linked post and is shown below.
template=im2bw(imread(http://www.clipartkid.com/images/543/floor-plan-symb-aT0MYg-clipart.png));
background=im2bw(imread(http://www.the-house-plans-guide.com/images/blueprints/draw-floor-plan-step-6.png));
bx = size(background, 2);
by = size(background, 1);
tx = size(template, 2); % used for bbox placement
ty = size(template, 1);
pos=[];
%// Change - Compute the cross power spectrum
Ga = fft2(background);
Gb = fft2(template, by, bx);
c = real(ifft2((Ga.*conj(Gb))./abs(Ga.*conj(Gb))));
%% find peak correlation
[max_c, imax] = max(abs(c(:)));
[ypeak, xpeak] = find(c == max(c(:))); % Added to make code work
if ~isempty(ypeak) || ~isempty(xpeak)
pos=position;
plot(xpeak,ypeak,'x','LineWidth',1,'Color','g');
rectangle('position',position,'edgecolor','b','linewidth',1, 'LineStyle', '- ');
end
How may I use the above code to detect multiple symbols as opposed to just one?
Amitay is correct in his assessment. BTW, the code that you took comes from the following post: Matlab Template Matching Using FFT.
The code is only designed to detect one match from the template you specify. If you wish to detect multiple templates, there are various methodologies you can try each with their own advantages and disadvantages:
Use a global threshold and from the cross power spectrum, any values that surpass this threshold deem that there is a match.
Find the largest similarity in the cross power spectrum, and anything that is some distance away from this maximum would be deemed that there is a match. Perhaps a percentage away, or one standard deviation away may work.
Try to make a histogram of the unique values in the cross power spectrum and find the point where there is a clear separation between values that are clearly uncorrelated with the template and values that are correlated. I won't implement this for you here because it requires that we look at your image then find the threshold by examining the histogram so I won't do that for you. Instead you can try the first two cases and see where that goes.
You will have to loop over multiple matches should they arise, so you'll need to loop over the code that draws the rectangles in the image.
Case #1
The first case is very simple. All you have to do is modify the find statement so that instead of searching for the location with the maximum, simply find locations that exceed the threshold.
Therefore:
%% find peak correlation
thresh = 0.1; % For example
[ypeak, xpeak] = find(c >= thresh);
Case #2
This is very similar to the first case but instead of finding values that exceed the threshold, determine what the largest similarity value is (already done), and threshold anything that is above (1 - x)*max_val where x is a value between 0 and 1 and denotes the percentage you'd like away from the maximum value to be considered as match. Therefore, if you wanted at most 5% away from the maximum, x = 0.05 and so the threshold now becomes 0.95*max_val. Similarly for the standard deviation, just find what it is using the std function and ensuring that you convert it into one single vector so that you can compute the value for the entire image, then the threshold becomes max_val - std_val where std_val is the standard deviation of the similarity values.
Therefore, do something like this for the percentage comparison:
%% find peak correlation
x = 0.05; % For example
[max_c, imax] = max(abs(c(:)));
[ypeak, xpeak] = find(c >= (1-x)*max_c);
... and do this for the standard deviation comparison:
std_dev = std(abs(c(:)));
[max_c, imax] = max(abs(c(:)));
[ypeak, xpeak] = find(c >= (max_c - std_dev));
Once you finally establish this, you'll see that there are multiple matches. It's now a point of drawing all of the detected templates on top of the image. Using the post that you "borrowed" the code from, the code to draw the detected templates can be modified to draw multiple templates.
You can do that below:
%% display best matches
tx = size(template, 2);
ty = size(template, 1);
hFig = figure;
hAx = axes;
imshow(background, 'Parent', hAx);
hold on;
for ii = 1 : numel(xpeak)
position = [xpeak(ii), ypeak(ii), tx, ty]; % Draw match on figure
imrect(hAx, position);
end

Matlab finding natural frequency, interp1 function creates NaN values

I created the following code in order to find the natural frequencies of a test sample which is excited by use of an impact hammer and has an accelerometer attached to it. However, I got stuck at interp_accelerance_dB_first. This interpolation creates a set of NaN values and I don't know why. I find it strange since interp_accelerance worked fine. I hope someone can help me!
N = 125000;
fs = 1/(x(2)-x(1));
ts = 1/fs;
f = -fs/2:fs/(N-1):fs/2;
% Set x-axis of graph
x_max = (N-1)*ts;
x_axis=0:ts:x_max;
% find the first natural frequency between these boundaries
First_lower_boundary = 15;
First_upper_boundary = 30;
Input = abs(fft(y)); %FFT input force
Output = abs(fft(o)); %FFT output acceleration
Accelerance = Output./Input;
bin_vals = [0 : N-1];
fax_Hz = bin_vals*fs/N;
N_2 = ceil(N/2);
% Interpolate accelerance function in order to be able to average all accelerance functions
Interp_accelerance = interp1(fax_Hz(1:N_2),Accelerance(1:N_2),x_axis);
% --- Find damping ratio of first natural frequency
% Determine the x-axis (from the boundries at the beginning of this script)
x_axis_first_peak = First_lower_boundary:ts:First_upper_boundary;
% Accelerance function with a logarithmic scale [dB]
Accelerance_dB_first = 20*log10(Accelerance(First_lower_boundary:First_upper_boundary));
% Interpolate the accelerance function [dB]
Interp_accelerance_dB_first = interp1(fax_Hz(First_lower_boundary:First_upper_boundary),Accelerance_dB_first,x_axis_first_peak);
Hard to say for sure without knowing what x,y,o are, but generally interp1 returns NaN when you try to interpolate outside of the bounds of the data's x-axis. Append the following at the end of your code:
[min(fax_Hz(First_lower_boundary:First_upper_boundary)),max(fax_Hz(First_lower_boundary:First_upper_boundary))]
[min(x_axis_first_peak),max(x_axis_first_peak)]
If the second segment doesn't fall inside of the first segment, then you've found your problem.
Incidentally, I think that interp_accelerance may be susceptible to the same error, again depending on the input parameters' exact nature.

Matlab plot of several digital signals

I'm trying to find a way to nicely plot my measurement data of digital signals.
So I have my data available as csv and mat file, exported from an Agilent Oscilloscope. The reason I'm not just taking a screen shot of the Oscilloscope screen is that I need to be more flexible (make several plots with one set of data, only showing some of the lines). Also I need to be able to change the plot in a month or two so my only option is creating a plot from the data with a computer.
What I'm trying to achieve is something similar to this picture:
The only thing missing on that pic is a yaxis with 0 and 1 lines.
My first try was to make a similar plot with Matlab. Here's what I got:
What's definitely missing is that the signal names are right next to the actual line and also 0 and 1 ticks on the y-axis.
I'm not even sure if Matlab is the right tool for this and I hope you guys can give me some hints/a solution on how to make my plots :-)
Here's my Matlab code:
clear;
close all;
clc;
MD.RAW = load('Daten/UVLOT1 debounced 0.mat'); % get MeasurementData
MD.N(1) = {'INIT\_DONE'};
MD.N(2) = {'CONF\_DONE'};
MD.N(3) = {'NSDN'};
MD.N(4) = {'NRST'};
MD.N(5) = {'1V2GD'};
MD.N(6) = {'2V5GD'};
MD.N(7) = {'3V3GD'};
MD.N(8) = {'5VGD'};
MD.N(9) = {'NERR'};
MD.N(10) = {'PGD'};
MD.N(11) = {'FGD'};
MD.N(12) = {'IGAGD'};
MD.N(13) = {'GT1'};
MD.N(14) = {'NERRA'};
MD.N(15) = {'GT1D'};
MD.N(16) = {'GB1D'};
% concat vectors into one matrix
MD.D = [MD.RAW.Trace_D0, MD.RAW.Trace_D1(:,2), MD.RAW.Trace_D2(:,2), MD.RAW.Trace_D3(:,2), ...
MD.RAW.Trace_D4(:,2), MD.RAW.Trace_D5(:,2), MD.RAW.Trace_D6(:,2), MD.RAW.Trace_D7(:,2), ...
MD.RAW.Trace_D8(:,2), MD.RAW.Trace_D9(:,2), MD.RAW.Trace_D10(:,2), MD.RAW.Trace_D11(:,2), ...
MD.RAW.Trace_D12(:,2), MD.RAW.Trace_D13(:,2), MD.RAW.Trace_D14(:,2), MD.RAW.Trace_D15(:,2)];
cm = hsv(size(MD.D,2)); % make colormap for plot
figure;
hold on;
% change timebase to ns
MD.D(:,1) = MD.D(:,1) * 1e9;
% plot lines
for i=2:1:size(MD.D,2)
plot(MD.D(:,1), MD.D(:,i)+(i-2)*1.5, 'color', cm(i-1,:));
end
hold off;
legend(MD.N, 'Location', 'EastOutside');
xlabel('Zeit [ns]'); % x axis label
title('Messwerte'); % title
set(gca, 'ytick', []); % hide y axis
Thank you guys for your help!
Dan
EDIT:
Here's a pic what I basically want. I added the signal names via text now the only thing that's missing are the 0, 1 ticks. They are correct for the init done signal. Now I just need them repeated instead of the other numbers on the y axis (sorry, kinda hard to explain :-)
So as written in my comment to the question. For appending Names to each signal I would recommend searching the documentation of how to append text to graph. There you get many different ways how to do it. You can change the position (above, below) and the exact point of data. As an example you could use:
text(x_data, y_data, Var_Name,'VerticalAlignment','top');
Here (x_data, y_data) is the data point where you want to append the text and Var_Name is the name you want to append.
For the second question of how to get a y-data which contains 0 and 1 values for each signal. I would do it by creating your signal the way, that your first signal has values of 0 and 1. The next signal is drawn about 2 higher. Thus it changes from 2 to 3 and so on. That way when you turn on y-axis (grid on) you get values at each integer (obviously you can change that to other values if you prefer less distance between 2 signals). Then you can relabel the y-axis using the documentation of axes (check the last part, because the documentation is quite long) and the set() function:
set(gca, 'YTick',0:1:last_entry, 'YTickLabel',new_y_label(0:1:last_entry))
Here last_entry is 2*No_Signals-1 and new_y_label is an array which is constructed of 0,1,0,1,0,....
For viewing y axis, you can turn the grid('on') option. However, you cannot chage the way the legends appear unless you resize it in the matlab figure. If you really want you can insert separate textboxes below each of the signal plots by using the insert ->Textbox option and then change the property (linestyle) of the textbox to none to get the exact same plot as above.
This is the end result and all my code, in case anybody else wants to use the good old ctrl-v ;-)
Code:
clear;
close all;
clc;
MD.RAW = load('Daten/UVLOT1 debounced 0.mat'); % get MeasurementData
MD.N(1) = {'INIT\_DONE'};
MD.N(2) = {'CONF\_DONE'};
MD.N(3) = {'NSDN'};
MD.N(4) = {'NRST'};
MD.N(5) = {'1V2GD'};
MD.N(6) = {'2V5GD'};
MD.N(7) = {'3V3GD'};
MD.N(8) = {'5VGD'};
MD.N(9) = {'NERR'};
MD.N(10) = {'PGD'};
MD.N(11) = {'FGD'};
MD.N(12) = {'IGAGD'};
MD.N(13) = {'GT1'};
MD.N(14) = {'NERRA'};
MD.N(15) = {'GT1D'};
MD.N(16) = {'GB1D'};
% concat vectors into one matrix
MD.D = [MD.RAW.Trace_D0, MD.RAW.Trace_D1(:,2), MD.RAW.Trace_D2(:,2), MD.RAW.Trace_D3(:,2), ...
MD.RAW.Trace_D4(:,2), MD.RAW.Trace_D5(:,2), MD.RAW.Trace_D6(:,2), MD.RAW.Trace_D7(:,2), ...
MD.RAW.Trace_D8(:,2), MD.RAW.Trace_D9(:,2), MD.RAW.Trace_D10(:,2), MD.RAW.Trace_D11(:,2), ...
MD.RAW.Trace_D12(:,2), MD.RAW.Trace_D13(:,2), MD.RAW.Trace_D14(:,2), MD.RAW.Trace_D15(:,2)];
cm = hsv(size(MD.D,2)); % make colormap for plot
figure;
hold on;
% change timebase to ns
MD.D(:,1) = MD.D(:,1) * 1e9;
% plot lines
for i=2:1:size(MD.D,2)
plot(MD.D(:,1), MD.D(:,i)+(i-2)*2, 'color', cm(i-1,:));
text(MD.D(2,1), (i-2)*2+.5, MD.N(i-1));
end
hold off;
%legend(MD.N, 'Location', 'EastOutside');
xlabel('Zeit [ns]'); % x axis label
title('Messwerte'); % title
% make y axis and grid the way I want it
set(gca, 'ytick', 0:size(MD.D,2)*2-3);
grid off;
set(gca,'ygrid','on');
set(gca, 'YTickLabel', {'0'; '1'});
ylim([-1,(size(MD.D,2)-1)*2]);

Plotting many lines as a heatmap

I have a large number (~1000) of files from a data logger that I am trying to process.
If I wanted to plot the trend from a single one of these log files I could do it using
plot(timevalues,datavalues)
I would like to be able to view all of these lines at same time in a similar way to how an oscilloscope has a "persistant" mode.
I can probably cobble together something that uses histograms but am hoping there is pre-existing or more elegant solution to this problem.
You can do exactly what you are suggesting yourself, i.e. plotting the heatmap of the signals.
Consider the following: I'll build a test signals (out of sine waves of different amplitude), then I'll plot the heatmap via hist3 and imagesc.
The idea is to build an auxiliary signal which is just the juxtaposition of all your time histories (both in x and y), then extract basic bivariate statistics out of that.
% # Test signals
xx = 0 : .01 : 2* pi;
center = 1;
eps_ = .2;
amps = linspace(center - eps_ , center + eps_ , 100 );
% # the auxiliary signal will be stored in the following variables
yy = [];
xx_f = [];
for A = amps
xx_f = [xx_f,xx];
yy = [yy A*sin(xx)];
end
% # final heat map
colormap(hot)
[N,C] = hist3([xx_f' yy'],[100 100]);
imagesc(C{1},C{2},N')
You can use also jet colormap instead of hot colormap for readability.
In the following the amplitude is gaussian instead of homogeneus.
here's a "primitive" solution that is just using hist:
%# generate some fake data
x=-8:0.01:8;
y=10*sinc(x);
yy=bsxfun(#plus,y,0.1*randn(numel(x),1000)' );
yy(randi(1000,1,200),:)= 5-randi(10)+ circshift(yy(randi(1000,1,200),:),[1 randi(numel(x),1,200)]);
%# get plot limit parameters
plot(x,yy)
yl=get(gca,'Ylim');
xl=get(gca,'Xlim');
close all;
%# set 2-d histogram ranges
ybins=100;
xbins=numel(x);
yrange=linspace(yl(1),yl(2),ybins);
xrange=linspace(xl(1),xl(2),xbins);
%# prealocate
m=zeros(numel(yrange),numel(xrange));
% build 2d hist
for n=1:numel(x)
ind=hist(yy(:,n),yrange);
m(:,n)=m(:,n)+ind(:);
end
imagesc(xrange,yrange,m)
set(gca,'Ydir','normal')
Why don't you normalize the data and then add all the lines together? You could then plot the heatmap from the single datafile.

How to create sliding window over signal on matlab

I have a sequence of data. So I want to plot that data inside the sliding windows due to windows length.
Help me please.
Actually data is from mean and variance of frames. So I want to plot that mean and variance inside the sliding windows. Also I can't create sliding windows on Matlab.
My approach would be,
a = randi(100,[1,50]); % My sequence
win_width = 10; %Sliding window width
slide_incr = 1; %Slide for each iteration
numstps = (length(a)-win_width)/slide_incr; %Number of windows
for i = 1:numstps
mean_win(i) = mean(a(i:i+win_width)); %Calculation for each window
end
plot(mean_win)
there may be better ways of doing it..
This is how I've always done it (adapted from code for 2 sliding windows). You can calculate the mean and variance however you'd like.
T = 25; % Window Size
K = size(data,1) - T; % Number of repetitions
for i = 1:K
window = data(i:i+T-1,:);
% Mean and Variance Calculations here
% Plotting here
% call 'drawnow' for incremental plotting (animation)
end
So if I understand you correctly you want to change the x-axis limits of the plot. Use xlim for that, for example:
a=1:10;
plot(a)
xmin = 5;
xmax = 7.6;
xlim([xmin xmax])
or if you want a window of a constant size you can xlim([xmin xmin+window]) etc...