Code covered by the BSD License  

Highlights from
Demo files for "MATLAB for Excel Users" webinar

image thumbnail

Demo files for "MATLAB for Excel Users" webinar

by

 

27 Aug 2010 (Updated )

This is the demo used in March 22, 2011 webinar "MATLAB for Excel Users".

ForecastGUI(varargin)
function varargout = ForecastGUI(varargin)
% FORECASTGUI M-file for ForecastGUI.fig
%      FORECASTGUI, by itself, creates a new FORECASTGUI or raises the existing
%      singleton*.
%
%      H = FORECASTGUI returns the handle to a new FORECASTGUI or the handle to
%      the existing singleton*.
%
%      FORECASTGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in FORECASTGUI.M with the given input arguments.
%
%      FORECASTGUI('Property','Value',...) creates a new FORECASTGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before ForecastGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to ForecastGUI_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help ForecastGUI

% Last Modified by GUIDE v2.5 05-Nov-2009 11:02:11

% Copyright 2010 The MathWorks, Inc.

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @ForecastGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @ForecastGUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before ForecastGUI is made visible.
function ForecastGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to ForecastGUI (see VARARGIN)

% Choose default command line output for ForecastGUI
handles.output = hObject;

% Create default plot
set(handles.axes1, 'Box', 'on');
view(handles.axes1, 3)
xlabel('Hour', 'FontSize', 12);
ylabel('Temperature (\circF)', 'FontSize', 12);
zlabel('Power (MW)', 'FontSize', 12);

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes ForecastGUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);

movegui(hObject, 'center')


% --- Outputs from this function are returned to the command line.
function varargout = ForecastGUI_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


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

[filename, pathname] = uigetfile('*.xls;*.xlsm;*.xlsx', 'Select data file');
if ~isequal(filename, 0)
  handles.data = importfile(fullfile(pathname, filename));
  set(handles.MonthList, 'enable', 'on');
  set(handles.DayList, 'enable', 'on');
  set(handles.ModelButton, 'enable', 'on');
  set(handles.HourText, 'enable', 'off');
  set(handles.TemperatureText, 'enable', 'off');
  set(handles.PredictButton, 'enable', 'off');
  
  set(handles.PowerText, 'String', '');
  
  cla(handles.axes1);
  
  handles.ptsH = plot3(NaN, NaN, NaN, '.', ...
    'MarkerSize', 15, 'Parent', handles.axes1);
  set(handles.axes1, ...
    'Box', 'on', ...
    'XLim', [min(handles.data.Hour), max(handles.data.Hour)], ...
    'YLim', [min(handles.data.Temperature), max(handles.data.Temperature)]);
  xlabel('Hour', 'FontSize', 12);
  ylabel('Temperature (\circF)', 'FontSize', 12);
  zlabel('Power (MW)', 'FontSize', 12);
  
  handles.modelH = [];
  handles.modelPtsH = [];
  handles.model = [];

  guidata(hObject, handles);
  
  updatePlot(handles);
end

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

selectedMonths = get(handles.MonthList, 'Value');
selectedDays = get(handles.DayList, 'Value');

idx = ismember(handles.data.DayOfWeek, selectedDays) & ...
  ismember(handles.data.Month, selectedMonths);

thisHour = handles.data.Hour(idx);
thisTemp = handles.data.Temperature(idx);
thisPower = handles.data.Power(idx);

handles.model = createFit(thisHour, thisTemp, thisPower);

if ~isempty(handles.modelH) && ishandle(handles.modelH)
  delete(handles.modelH);
end
if ~isempty(handles.modelPtsH) && ishandle(handles.modelPtsH)
  delete(handles.modelPtsH);
end
handles.modelH = plot(handles.model, 'Parent', handles.axes1);
% set(handles.modelH, 'FaceColor', 'none');
set(handles.modelH, 'FaceAlpha', 0.5);
handles.modelPtsH = line(thisHour, thisTemp, thisPower, ...
  'Parent', handles.axes1, 'linestyle', 'none', 'marker', '.', ...
  'color', 'red', 'markersize', 10);

guidata(hObject, handles)

set(handles.HourText, 'enable', 'on');
set(handles.TemperatureText, 'enable', 'on');
set(handles.PredictButton, 'enable', 'on');

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

if isempty(handles.model)
  return
end

% Get Hour and Temperature inputs
hr = str2double(get(handles.HourText, 'String'));
tp = str2double(get(handles.TemperatureText, 'String'));

% Evaluate using model
[p_ci, p_predict] = predint(handles.model, [hr, tp]);


set(handles.PowerText, 'String', sprintf('%0.2f MW', p_predict));
title(handles.axes1, ...
  sprintf('Power Prediction: %0.2f MW (%0.2f, %0.2f)', p_predict, p_ci), ...
  'FontSize', 12, 'FontWeight', 'bold');


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

% Hints: get(hObject,'String') returns contents of HourText as text
%        str2double(get(hObject,'String')) returns contents of HourText as a double


% --- Executes during object creation, after setting all properties.
function HourText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to HourText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



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

% Hints: get(hObject,'String') returns contents of TemperatureText as text
%        str2double(get(hObject,'String')) returns contents of TemperatureText as a double


% --- Executes during object creation, after setting all properties.
function TemperatureText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to TemperatureText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in MonthList.
function MonthList_Callback(hObject, eventdata, handles)
% hObject    handle to MonthList (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 MonthList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from MonthList

updatePlot(handles)

% --- Executes during object creation, after setting all properties.
function MonthList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to MonthList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in DayList.
function DayList_Callback(hObject, eventdata, handles)
% hObject    handle to DayList (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 DayList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from DayList

idx = get(hObject,'Value');
if idx == 8
  set(hObject, 'Value', 1:5);
elseif idx == 9
  set(hObject, 'Value', 6:7);
end

updatePlot(handles);

% --- Executes during object creation, after setting all properties.
function DayList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to DayList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function updatePlot(handles)

selectedMonths = get(handles.MonthList, 'Value');
selectedDays = get(handles.DayList, 'Value');

idx = ismember(handles.data.DayOfWeek, selectedDays) & ...
  ismember(handles.data.Month, selectedMonths);

thisHour = handles.data.Hour(idx);
thisTemp = handles.data.Temperature(idx);
thisPower = handles.data.Power(idx);

set(handles.ptsH, ...
  'XData', thisHour, ...
  'YData', thisTemp, ...
  'ZData', thisPower);

function [fitresult, gof] = createFit(thisHour, thisTemp, thisPower)
%CREATEFIT(THISHOUR,THISTEMP,THISPOWER)
%  Fit surface to data.
%
%  Data for 'untitled fit 1' fit:
%      X Input : thisHour
%      Y Input : thisTemp
%      Z output: thisPower
%      Weights : (none)
%
%  Output:
%      fitresult : an sfit object representing the fit.
%      gof : structure with goodness-of fit info.

ft = fittype( 'a0 + a1*cos(w*x) + b1*sin(w*x) + a2*cos(2*w*x) + b2*sin(2*w*x) + c1*y^2 + c2*y', 'indep', {'x', 'y'}, 'depend', 'z' );
opts = fitoptions( ft );
opts.Display = 'Off';
opts.Lower = [-Inf -Inf -Inf -Inf -Inf -Inf -Inf -Inf];
opts.StartPoint = [0.394215930761206 0.245616861988953 0.989843778259555 0.812507848600185 0.812489348000533 0.945905873253906 0.185190354480726 0.508414206620238];
opts.Upper = [Inf Inf Inf Inf Inf Inf Inf Inf];
opts.Weights = zeros(1,0);
[fitresult, gof] = fit( [thisHour, thisTemp], thisPower, ft, opts );


function dataByColumn1 = importfile(fileToRead1)
%IMPORTFILE(FILETOREAD1)
%  Imports data from the specified file
%  FILETOREAD1:  file to read

%  Auto-generated by MATLAB on 24-Sep-2009 22:05:41

% Import the file
sheetName='Sheet1';
[numbers, strings] = xlsread(fileToRead1, sheetName);
if ~isempty(numbers)
  newData1.data =  numbers;
end
if ~isempty(strings)
  newData1.textdata =  strings;
  newData1.colheaders =  strings;
end

% Break the data up into a new structure with one field per column.
colheaders = genvarname(newData1.textdata);
for i = 1:length(colheaders)
  dataByColumn1.(colheaders{i}) = newData1.data(:, i);
end

Contact us