Monday, October 23, 2017

[Matlab GUI] Plot UI: Data processing tool

It is import to know how to visualize and analyze numerical data generated after either simulation or testing. With a variety of functions of Matlab, it can be easily implemented to visualize and analyze numerical data. However, not only it is often required to buy additional licenses but also we should know how to use functions. Moreover, raw data often requires processing to change its format or structure to draw plots. 
Plot UI is the generic data processing tool which is designed to alleviate these problems. It offers four plotting modes which can draw plots with variables both from *.mat files and on the workspace of Matlab.

(24 Oct 2017)
Plotting mode
l  Plot
l  FFT (Fast Fourier Transform)
l  PSD (Power Spectral Density)
l  Bode Plot

Line property
l  Color
l  Style
l  Width
l  Marker
l  Delete

Axis property
l  Axis label
l  Range
l  Log/Linear scale
l  Title
It does not support FFT and Bode plot.

Example
1. Bode Plot

2. Plot 

3. FFT

4. PSD


Wednesday, October 18, 2017

[Matlab] PSD (Power Spectral Density)

https://www.mathworks.com/help/signal/ug/power-spectral-density-estimates-using-fft.html

Example
-------------------------------------------
function handles = PSDPlotFnc(hObject,eventdata,handles)

% Load the data
result = handles.result;
% Retrieve x data
xi = get(handles.xVariables,'Value');
t = result{xi,1};
% Retrieve y data
yn = get(handles.VariablesList,'String');
yi = get(handles.VariablesList,'Value');
yn = yn{yi,1}; y = result{yi,1};

% Sampling time Ts and sampling frequency Fs
Ts = t(2) - t(1);
Fs = 1/Ts;

% Data length
N = length(y);

% FFT
ydft = fft(y);
ydft = ydft(1:N/2+1);
psdy = ( 1+(Fs*N) ) * abs(ydft).^2;
psdy(2:end-1) = 2*psdy(2:end-1);
freq = 0:Fs/length(y):Fs/2;

% Plot
pline = plot(handles.axes1,freq,10*log10(psdy),'DisplayName',yn);
hl = legend(handles.axes1,'-DynamicLegend');
set(hl,'interpreter','none');
xlabel(handles.axes1,'Frequency [Hz]');
ylabel(handles.axes1,'Power/Frequency [dB/Hz]');
grid(handles.axes1,'on');


[Matlab] FFT (Fast Fourier Transform)

https://www.mathworks.com/help/matlab/ref/fft.html

Matlab computes DFT(Discrete Fourier Transform) using a FFT algorithm.

Example
-------------------------------------
% Discrete Fourier Transform (DFT)
function handles = DFTPlotFnc(hObject,eventdata,handles)

% Load the data
result = handles.result;
% Retrieve x data
xi = get(handles.xVariables,'Value');
t = result{xi,1};
% Retrieve y data
yn = get(handles.VariablesList,'String');
yi = get(handles.VariablesList,'Value');
yn = yn{yi,1}; y = result{yi,1};

% Sampling time Ts and sampling frequency Fs
Ts = t(2) - t(1);
Fs = 1/Ts;

% Data length L
L = length(y);
% Number of FFT points,
% nextpow2 returns the exponents for the smallest powers of two that satisfy 
nfft = 2^nextpow2(L);

% Frequency
freq = (Fs/2) * linspace(0,1,nfft/2+1);
% Discrete Fourier Transform(DFT)
normalizedFFT = fft(y,nfft)/L; % with zero-padding 

% Plot
pline = plot(handles.axes2,freq,2*abs(normalizedFFT(1:nfft/2+1)),'DisplayName',yn);
dftleg = legend(handles.axes2,'-DynamicLegend');
set(dftleg,'interpreter','none');

xlabel(handles.axes2,'Frequency [Hz]');
ylabel(handles.axes2,'FFT |Y(f)|','interpreter','none');
grid(handles.axes2,'on');

originaline = plot(handles.axes3,t,y,'DisplayName',yn);
orileg = legend(handles.axes3,'-DynamicLegend');
set(orileg,'interpreter','none');
xlabel(handles.axes3,'Time [sec]');
ylabel(handles.axes3,[yn ' Original'],'interpreter','none');
grid(handles.axes3,'on');

Tuesday, September 26, 2017

License conditions

Copyright (c) 2015, 'name'
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

Monday, August 14, 2017

[Matlab] Bode plot without Control Toolbox

When it comes to Bode plot, it is easy to draw a Bode plot with control toolbox, but Not everybody can get this toolbox.
For those who don't have Control Toolbox, let's see how to draw a Bode plot with only basic Matlab functions.

Assuming that a transfer function is as below.
     1
  -------
   s + 1

Then, the magnitude and phase of the transfer function are neccsary for bode plot.
The magnitude and phase can be calculated by replacing s with jw.
where, j is the imaginary unit of complex number, and w is the frequency.

     1                                  1
  -------          -->         -----------
   s + 1                          j*w + 1

Possible matlab code for bode plot is as below.
--------------------------------------------------------
% Define frequency
freq = 0.01:0.01:1000;

% Transfer function
tf = 1 ./ (1 + i*freq);

% Magnitude
m = 20 * log10(abs(tf));

% Phase
phase = angle(tf);

% Plot
subplot(2,1,1)
semilogx(freq,m);
grid on
ylabel('Magnitude (dB)');

subplot(2,1,2)
semilogx(freq,phase);
grid on
ylabel('Phase (deg)');
xlabel('Frequency (rad/sec)');
--------------------------------------

As a result of the code above,


-----------------------------------------------------------------------
General method for Bode plot

% Define the numerator and denominator
num=[-0.1, -2.4, -181, -1950];
den = [1, 3.3, 990,2600];
tnum = [];
tden = [];
an = length(num);
bn = length(den);

% Numerator
for N = 1:1:an
    if num(N) > 0
        si ='+';
    elseif num(N) <0 p="">
        si = '';
    end
        
    temp = sprintf('%s%d%s%s%d ',si,num(N),'*','s.^',an-N);
    tnum = [tnum temp];
end

% Denominator
for N = 1:1:length(den)
    if den(N) > 0
        si ='+';
    elseif den(N) <0 p="">
        si = '-';
    end
        
    temp = sprintf('%s%d%s%s%d ',si,den(N),'*','s.^',bn-N);
    tden = [tden temp];
end
% Define a system transfer function
sys = @(s) eval(tnum)./ eval(tden);
% Define frequency as x 
w=0.01:0.01:1000;
% Magnitude (dB)
amp=20*log10(abs(sys(w*1i)));
% Phase
ang=angle(sys(w*1i))*180/pi;

% Plot using subplot
subplot(211)
semilogx(w,amp);
ylabel('Magnitude (dB)')
grid on

subplot(212)
semilogx(w,ang);
xlabel('frequency (rad/sec)')
ylabel('phase (deg)')
grid on