Sunday, July 30, 2017

[Matlab] Plot the latitude and longitude information on Google Map

Source URL
1. https://www.mathworks.com/matlabcentral/fileexchange/27627-zoharby-plot-google-map
2. https://blogs.mathworks.com/pick/2012/05/04/plot-google-map/

Can download the function 'plot_google_map' from the source URL 1.

Example code 1.
lat = [48.8708 51.5188 41.9260 40.4312 52.523 37.982];
lon = [2.4131 -0.1300 12.4951 -3.6788 13.415 23.715];
plot(lon,lat,'.r','MarkerSize',20)
plot_google_map

Result 1
The result appears on new figure.

Example code 2
% load route data
load NatickToBOS

% plot route data
plot(Data001(:, 1), Data001(:, 2), 'r', 'LineWidth', 2);
line(Data001(1, 1), Data001(1, 2), 'Marker', 'o', ...
    'Color', 'b', 'MarkerFaceColor', 'b', 'MarkerSize', 10);
line(Data001(end, 1), Data001(end, 2), 'Marker', 's', ...
    'Color', 'b', 'MarkerFaceColor', 'b', 'MarkerSize', 10);
xlim([-71.4, -71]); axis equal off

% Google map
plot_google_map('maptype', 'roadmap');

zoomHandle = zoom;
set(zoomHandle, 'ActionPostCallback', @update_google_map);

Result 2
The result appears on new figure.



[Matlab GUI] Build simple Data Processing tool - 5/5

5. Clear the axes, and Move the figure to new figure (Undock)

After drawing a plot, you can either clear the plot or undock the plot from the axes.

1) Clear
function Clear_ClickedCallback(hObject, eventdata, handles)
% hObject    handle to Clear (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
try
    cla(all,'reset'); % Clear the entire axes and remove the y-axis
catch
    cla();
end
handles.legend = [];
legend off;
set(handles.axes1,'Position',handles.inipos);

2) Undock
function Undock_ClickedCallback(hObject, eventdata, handles)
% hObject    handle to Undock (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

warning('off');

fig_children = get(gcf,'children');
fig_Axes = findall(fig_children,'Type','Axes');
fig_legend = findall(fig_children,'Tag','legend');
fig = figure;

% copy an existing post from gui to new figure window
copyobj(fig_Axes,fig);

% Delete the legends because the size is not well-suited
dleg = findall(fig,'Tag','legend'); delete(dleg);

% Clear an offset in position of an existing post so it can be centered on a new figure window 
set(gca,'ActivePositionProperty','outerposition');
set(gca,'Units','normalized');
set(gca,'OuterPosition',[0 0 1 1]);
set(gca,'position',[0.1200 0.1100 0.790 0.8150]);

% Change the default logo on the new figure appeared.
try 
    imgPath = fullfile(pwd,'itk.jpg');
    javaFrame = get(handle(gcf),'JavaFrame');
    javaFrame.setFigureIcon(javax.swing.ImageIcon(imgPath)); 
catch
    if code == 1
        warndlg('1','error');
    elseif code == 2
        warndlg('2','error')
    end
end
% Set the legend on the new figure
l = legend('show'); set(l,'Interpreter','none');
warning('on');

Related Posts
0. Build simple plot tool
1. Create a tool layout in GUIDE
2. Load mat file in structure array, and Display the file list loaded on the listbox
3. Diplay variables of mat file, and Plot variables on the axes
4. How to add new plot to the existing plot, and Use dynamic legend
5. Clear the axes, and Move the figure to new figure (Undock)

[Matlab GUI] Build simple Data Processing tool - 4/5

4. How to add new plot to the existing plot, and Use dynamic legend

After selecting either one variable or two variables, we can both draw a plot and add the legend dynamically on the axes selected.

Example code
-----------------------------------------------------------
% Create a legend name
tleg = handles.legend(1:end-4);
yvar = get(handles.VariablesList,'String');
yvari = get(handles.VariablesList,'Value');
ytemp = yvar(yvari);
% Legend name: filename + variable name
leg = sprintf('%s%s%s',tleg,': ',ytemp{1});
% Get the data of y
result = handles.result;
y = result{yvari,1};

if isequal(checkp,1)% with x-axis variable selected
   % Get the data of x
   xn = get(handles.xVariables,'String');
   xi = get(handles.xVariables,'Value'); xn=xn{xi,1};
   x = result{xi,1};
   % Plot and update the legend dynamically
   pline = plot(handles.axes1,x,y,'DisplayName',leg);
   hl = legend(handles.axes1,'-DynamicLegend');
   xlabel(xn,'interpreter','none');
   ylabel(ytemp{1},'interpreter','none');
else % Without x variable
   % Plot and update the legend dynamically   
   pline = plot(handles.axes1,y,'DisplayName',leg);
   hl = legend(handles.axes1,'-DynamicLegend');
   ylabel(ytemp{1},'interpreter','none');
end
% Set the legend interpreter to none
set(hl,'Interpreter','none');


Related posts
0. Build simple plot tool.
1. Create a tool layout in GUIDE
2. Load mat file in structure array, and Display the file list loaded on the listbox
3. Display variables of mat file, and Plot variables on the axes
4. How to add new plot to the existing plot, and Use dynamic legend
5. Clear the axes, and Move the figure to new figure (Undock)

[Matlab GUI] Build simple Data Processing tool - 3/5

3. Display variables of mat file, and Plot variables on the axes

After loading a mat file in structure type, click a mat file, and then variables in the mat file selected will appear on the two pop-up menus of X and Y.
With one or two variables selected, we can draw a plot on the axes.

To implement these functions, one is to know each variable saved in a mat file, and the other is to draw a plot with variables selected.

1) Know each variable in a mat file
After clicking a mat file on the listbox, variables in a mat file in the structure type displays on the two pop-up handles.

Create a callback function of the listbox as below.

------------------------------------------------------------------------
function FileList_Callback(hObject, eventdata, handles)
% hObject    handle to FileList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns FileList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from FileList
try
    index = get(handles.FileList,'Value');
    file = get(handles.FileList,'String');
    filename = file(index); filename = filename{1,1};
    filenamePath = fullfile(handles.directory,filename);
catch% ME
    %warndlg(ME.message);
    return;
end

% check a file extension
comma = strfind(filenamePath,'.');
extension = filenamePath(comma(1)+1:end);

switch extension
    case 'mat'     
        result = load(filenamePath); % load structure mat file
        VariableList = fieldnames(result); % extract field names
        handles.result = struct2cell(result);     
        % Display variables on the pop-up of Y       
        set(handles.VariablesList,'String',VariableList);     
        % Display variables on the pop-up of X
        set(handles.xVariables,'String',VariableList);     

handles.legend = filename;
set(handles.selectedFile,'String',filename);
guidata(hObject,handles);
-------------------------------------------------------------------------


2) Draw a plot

% --- Executes on button press in postprocessing
function plot_Callback(hObject, eventdata, handles)
% hObject    handle to postprocessing_ui (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

warning('off');
index = get(handles.VariablesList,'Value');
holdaxis = get(handles.holdon,'Value');
checkp = get(handles.xPlotCheck,'Value'); % x-axis on/off check

% is the plot handles field defined for the handles structure?
if ~isfield(handles,'pline');
    handles.pline = [];% handles.pline will be used afterward.
end

try
    % create a legend name
    tleg = handles.legend(1:end-4);
    yvar = get(handles.VariablesList,'String');
    yvari = get(handles.VariablesList,'Value'); ytemp = yvar(yvari);
    leg = sprintf('%s%s%s',tleg,': ',ytemp{1});

    result = handles.result;
    y = result{index,1};

    % Hold on
    if isequal(holdaxis,1)
        hold(handles.axes1,'all');
        if isequal(checkp,1)% with x-axis variable selected
            xn = get(handles.xVariables,'String');
            xi = get(handles.xVariables,'Value'); xn = xn{xi,1};
            x = result{xi,1};
            pline = plot(handles.axes1,x,y,'DisplayName',leg);
            hl = legend(handles.axes1,'-DynamicLegend');
            xlabel(xn,'interpreter','none');
            ylabel(ytemp{1},'interpreter','none');
        else % default
            pline = plot(handles.axes1,y,'DisplayName',leg);
            hl = legend(handles.axes1,'-DynamicLegend');
            ylabel(ytemp{1},'interpreter','none');
        end         

        set(hl,'Interpreter','none');
 
    % Hold off
    else
        % Initialization of handles.pline
        handles.pline = [];
     
        hold(handles.axes1,'off');
        if isequal(checkp,1)% with x-axis variable selected
            xn = get(handles.xVariables,'String');
            xi = get(handles.xVariables,'Value'); xn = xn{xi,1};
            x = result{xi,1};
            pline = plot(handles.axes1,x,y,'DisplayName',leg);
            hl = legend(handles.axes1,'-DynamicLegend');
            xlabel(xn,'interpreter','none');
            ylabel(ytemp{1},'interpreter','none');
        else % default   
            pline = plot(handles.axes1,y,'DisplayName',leg);
            hl = legend(handles.axes1,'-DynamicLegend');
            ylabel(ytemp{1},'interpreter','none');
        end
        set(hl,'Interpreter','none');
    end
 
    % update the plot handles to the array of plot handles
    handles.pline = [handles.pline ; pline];
    guidata(hObject,handles);
    grid(handles.axes1,'on');
 
    % Save the plot legend
    handles.hl = hl;
    guidata(hObject,handles);
 
catch ME
    warndlg(ME.message,'No data files');
    guidata(hObject,handles);
    %warndlg('Please first load data files','No data files');
end




Related posts
0. Build simple plot tool.
1. Create a tool layout in GUIDE
2. Load mat file in structure array, and Display the file list loaded on the listbox
3. Display variables of mat file, and Plot variables on the axes
4. How to add new plot to the existing plot, and Use dynamic legend
5. Clear the axes, and Move the figure to new figure (Undock)

[Matlab GUI] Build simple Data Processing tool - 2/5

2. Load mat file in structure array, and Display file list loaded on the listbox

We here create the function which loads *.mat file in structure array type. The button 'Load' shown below will call this function.

Before adding the function into the button 'Load', some setting should be done in advance.
1) Right-click on the button 'Load'.
2) Select the menu 'Property Inspector'. Then, the figure below will appear.
3) Change the Tag name on the Property Inspector window above.
As in the same way, change the Tag name of the Listbox.

4) In the pop-up menu appearing by the right-click on the button 'Load',
select the menu 'View Callbacks > Callback'. Then, the corresponding function is added and m-script appears on the screen as below.
Here, the tag name defined at 3) becomes the name of callback function.

 * Create a load callback function
1) To open and select *.mat files, the file directory is necessary.
It is easily obtained using the Matlab function 'uigetdir'.

directory = uigetdir(' ','Select a folder');

2) Get file list

result = dir(directory);
allist = struct2cell(result);
s=size(allist); n=s(2)-2; list=cell(1,n);
for N=1:1:n
    list{1,N} = allist{1,N+2};
end

3) Filtering the list

matfile = ~cellfun(@isempty,strfind(list,'.mat'));
mf = double(matfile);
total = logical(mf);
list = list(total);

4) Display the filtered list
Supposing that the Tag name of the Listbox is 'FileList', file list can be displayed using the command below.

set(handles.FileList,'String',list);

After all, the code looks as following.
%
directory = uigetdir(' ','Select a folder');
%
result = dir(directory);
allist = struct2cell(result);
s=size(allist); n=s(2)-2; list=cell(1,n);
for N=1:1:n
    list{1,N} = allist{1,N+2};
end
%
matfile = ~cellfun(@isempty,strfind(list,'.mat'));
mf = double(matfile);
total = logical(mf);
list = list(total);
%
set(handles.FileList,'String',list);


Related posts
0. Build simple plot tool.
1. Create a tool layout in GUIDE
2. Load mat file in structure array, and Display the file list loaded on the listbox
3. Display variables of mat file, and Plot variables on the axes
4. How to add new plot to the existing plot, and Use dynamic legend
5. Clear the axes, and Move the figure to new figure (Undock)

Monday, July 17, 2017

[Matlab GUI] Build simple Data Processing tool - 1/5

1. Create a tool layout in GUIDE
There are two ways to create UI(User Interface) in Matlab. One is to create UIs programmatically, and the other is to create UIs using Matlab app called GUIDE.
Both can do almost the same thing, but some syntax are different, and developing UIs programmatically takes more time. If you are new to UI development, GUIDE is recommended. Anyway, let's bring it on.

Before getting started, see https://www.mathworks.com/help/matlab/creating_guis/about-the-simple-guide-gui-example.html

# Getting started with GUIDE layout editor
1) Start GUIDE by typing 'guide' on the Matlab command window

2) 'GUIDE Quick Start' window appears, then click 'OK'.

3) Layout editor


# Create an UI
1) Component name.

2) Add the components in the layout edit as below.
  3 pushbuttons, 2 static texts, 2 pop-up menus, 1 listbox, and 1 axes

3) After layout, save the figure.
  'File > Save' or 'Ctrl+S'
  After save, you see m script created automatically. This m script is used to insert functions to implement the UI created by GUIDE above.




Related posts
0. Build simple plot tool.
1. Create a tool layout in GUIDE
2. Load mat file in structure array, and Display the file list loaded on the listbox
3. Display variables of mat file, and Plot variables on the axes
4. How to add new plot to the existing plot, and Use dynamic legend
5. Clear the axes, and Move the figure to new figure (Undock)









Thursday, July 13, 2017

[Matlab GUI] Build simple Data Processing tool - 0/5

Matlab can easily plot variables with the powerful functions provided as default, but often annoying to define at least x vector and y vector on the command window, especially when plotting variables of structure format of mat file.
In order to draw figures, first of all you should load *.mat file to the workspace, and second, determine variables to plot, and then can draw a figure using the function 'plot'. In addition to this, you can also use the function, 'legend', 'xlabel', 'ylabel', etc.
If you want to add line plot to the existing figure, you can use 'hold on' or 'hold all'.

It is not that difficut to do what has been explained so far, but would be more happy if you have some convenient tool. This kind of simple tool can be developed by Matlab GUIDE.
Let me post how to create it with GUIDE. Let's make it together.

Related posts
1. Create a tool layout in GUIDE
2. Load mat file in structure array, and Display the file list loaded on the listbox
3. Display variables of mat file, and Plot variables on the axes
4. How to add new plot to the existing plot, and Use dynamic legend
5. Clear the axes, and Move the figure to new figure (Undock)

Wednesday, July 12, 2017

[Matlab] Create a log file using 'fopen', 'fprintf', and 'fclose'

A log file is often required to write warnings, errors, and etc while running a simulation, so we can know what has happened during the simulation.
Let's see how to create a log file with Matlab.

----------------------------------------------
% Variables and data
variable = {'engine','tm','driver'};
data = [1, 2, 3;4, 5, 6;7, 8, 9];

% Path
path =[pwd,'\Configuration'];
name = 'log.txt';
file = fullfile(path,name);
[fid,msg] = fopen(file,'w+'); % 'w+' open a file for adding to end line
if fid == -1
    error(msg);
else
    % Start date and time
    sStart = clock;
    sStart = sprintf('%d%s%d%s%d%s%d%s%d%s',sStart(1),'-',sStart(2),'-',...
        sStart(3),', ',sStart(4),'h',sStart(5),'m');
    fprintf(fid,'%s%s\n','Start : ',sStart);
 
    % Write variables
    for N=1:1:length(variable)
        if N < length(variable)
            fprintf(fid,'%s\t\t',variable{N});
        elseif N == length(variable)
            fprintf(fid,'%s\n',variable{N});
        end
     
    end
 
    fprintf(fid,'%d\t\t%d\t\t%d\n',data);
 
    % End date and time
    sEnd = clock;
    sEnd = sprintf('%d%s%d%s%d%s%d%s%d%s',sEnd(1),'-',sEnd(2),'-',sEnd(3),...
        ', ',sEnd(4),'h',sEnd(5),'m');
    fprintf(fid,'%s%s\n','End : ',sEnd);
end
fclose(fid);
--------------------------------------------------

As a result of the code above, the following log is created.
------------------------------------
Start : 2017-7-13, 10h33m
engine tm driver
1 4 7
2 5 8
3 6 9
End : 2017-7-13, 10h33m
---------------------------------------

% fopen option
FID = fopen(FILENAME,PERMISSION) opens the file FILENAME in the
    mode specified by PERMISSION:
 
        'r'     open file for reading
        'w'     open file for writing; discard existing contents
        'a'     open or create file for writing; append data to end of file
        'r+'    open (do not create) file for reading and writing
        'w+'    open or create file for reading and writing; discard
                existing contents
        'a+'    open or create file for reading and writing; append data
                to end of file
        'W'     open file for writing without automatic flushing
        'A'     open file for appending without automatic flushing


Monday, July 10, 2017

[Matlab GUI] Uitab and ButtonDownFcn

Using 'ButtonDownFcn', advanced functions can be implemented in MATLAB GUIDE.

For example, depending on the tab selected by clicking, strings displayed on the buttons can be changed. See the example below.

1. Place the code below into the XXX_OpeningFcn
--------------------------------
% Suppress an annoying warning message
warning off MATLAB:uitabgroup:OldVersion

%---- Create a tab group
handles.tgroup = uitabgroup('Parent',handles.mainGui,'TabLocation','top');
% Set position [left, bottom, width, height], normalized unit
set(handles.tgroup,'Units','Normalized','Position',[0 0 1 0.945]);
% Create each tab
handles.maintab = uitab('Parent',handles.tgroup,'Title','  Main  ',...
    'ButtonDownFcn',@tabmain);
handles.doetab = uitab('Parent',handles.tgroup,'Title','  DoE   ',...
    'ButtonDownFcn',@tabdoe);
handles.simulinktab = uitab('Parent',handles.tgroup,'Title','Simulink',...
    'ButtonDownFcn',@tabsimulink);
% Place panels into each tab
set(handles.Tab1,'Parent',handles.maintab);
set(handles.Tab2,'Parent',handles.doetab);
set(handles.Tab3,'Parent',handles.simulinktab);

% Reposition each panel to the same location as Tab1
set(handles.Tab2,'Position',get(handles.Tab1,'Position'));
set(handles.Tab3,'Position',get(handles.Tab1,'Position'));
--------------------------------------------------------------------------------

2. Create functions tabmain, tabdoe, and tabsimulink
One of three functions could be created as below.

-----------------------------------
% When clicking the tab 'DoE '
function tabdoe(hObject,~,~)
 
handles = guidata(hObject);
% Enable buttons
set(handles.Run,'Enable','on');
set(handles.ImportAll,'Enable','on');
set(handles.ExportAll,'Enable','on');
% Set button string
set(handles.Run,'String','Run(D)');
set(handles.ImportAll,'String','Load');
set(handles.ExportAll,'String','Save');

guidata(hObject,handles);
-----------------------------------------



Related Post
1. Create tabs using uitab and uitabgroup

Wednesday, July 5, 2017