⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chaingui.m

📁 Matlab中优化多个矩阵相乘以提高计算效率的源代码。
💻 M
📖 第 1 页 / 共 3 页
字号:
    ActivateHelpWhatsThis(hfig);end% --------------------------------------------------------------function DeactivateHelpWhatsThis(hfig)ud = get(hfig,'userdata');if ~ud.Help.IsActive, return; endud.Help.IsActive = 0;% Restore pointer icon quickly:setptr(hfig,'arrow');% Shut off button-down functions for uicontrols and the figure:set(ud.Help.hChildren, 'ButtonDownFcn','');set(ud.Help.hEnabled, 'enable','on');ListCallback([],[],hfig);  % Update GUI enables, etcset(hfig,'userdata',ud);% --------------------------------------------------------------function ActivateHelpWhatsThis(hfig)% Get state:ud = get(hfig,'userdata');if ud.Help.IsActive, return; endud.Help.IsActive = 1;% Change pointer icon:setptr(hfig,'help');% Install button-down functions on all uicontrols,%  plus the figure itself:% uicontrol, axes, line, patch, textud.Help.hChildren = findobj(hfig);set(ud.Help.hChildren, 'ButtonDownFcn', @HelpWhatsThisBDown);% NOTE: Enabling context-help "destroys" the enable-state%  of all uicontrols in the GUI.  When the callback completes,%  we must restore the enable states.%hEna=findobj(ud.Help.hChildren,'enable','on');ud.Help.hEnabled=hEna;for i=1:length(hEna),   try, set(hEna(i),'enable','inactive');   catch,   endendset(hfig,'userdata',ud);% --------------------------------------------------------------function HelpTopicsCB(hco, eventStruct)% HelpTopicsCB Get reference-page helphelpwin(mfilename);% --------------------------------------------------------------function HelpGeneral(hco, eventStruct, tag)% HelpGeneralhfig = gcbf;%hco = gcbo;if nargin<3,   tag = get(hco,'tag');endif ~ischar(tag),   tag = 'WT?';endmsg = '';% Strip off the 'WT?' tag prefix:tag=tag(4:end);switch tagcase ''   msg = {'';      'No help available on selected item.'};case 'Chain Multiplication GUI'    msg = {'';        'This is the Chain Multiplication GUI.';        '';        'Performs optimization of a specified matrix multiply';        'chain by determining the parenthesization of';        'multiplicands that best minimizes two metrics:';        '';        '- the maximum size of all temporary matrices that';        '  must be stored in memory at any time during the';        '  evaluation, and';        '- the total number of floating point operations';        '  (flops) required to compute the result.';        '';        'See the Help menu for more information';        'on CHAINGUI and CHAINMULT.'};case 'Result List'   msg = {'';      'Displays a list of optimization results for all';      'possible parenthesizations of the specified';      'matrix multiply problem.  Three possible';      'optimization results may appear:'      '';      '   - flops & storage (jointly minimized)';      '   - flops then storage (minimized in order)';      '   - storage then flops (minimized in order)';      ''};case 'Matrix Sizes'   % This help is selected for both the "Specify matrix sizes"   % and the "MATLAB Expression modes.  However, specific   % help is desired for each mode   %   ud = get(hfig,'userdata');      if isSizeMode(ud),      % "Specify matrix sizes" mode      tag='Matrix size list';      msg = {'';         'This is where the list of matrix sizes is specified';         'prior to optimization.  This information must be';         'entered as a cell-array of size vectors.';         '';         'For example, if you have 3 matrices with the sizes';         '4x5, 5x5, and 5x4, you would enter the expression:';         '       { [4 5][5 5][5 4] }';         '';         'Only real matrices may be specified in this mode.';         'For complex matrices or general expressions, use';         '"Specify MATLAB Expression" mode.';      };   else      % "Specify MATLAB Expression" mode      tag='MATLAB Expression' ;      msg = {'';         'This is where the matrix expression is specified';         'prior to optimization.  The expression may contain';         'expressions and multiplication (*) symbols.';         'Note that a distinction is made between real and';         'complex matrices and will affect the optimization.';         '';         'For example, if you wish to multiply the matrices';         'U'' * V * U, enter the expression exactly as it appears.';         'Only simple chain matrix expressions will be accepted';         'in the form: expr1 * expr2 * expr3 * ...';         '';         'For entry of matrix size information without the';         'corresponding MATLAB matrices in the workspace,';         'use "Specify matrix sizes" mode.';      };   end   case 'Status Bar'   msg = {'';      'The status bar displays information about a command';      'or toolbar button, or an operation in progress.'};case 'Random Matrices'    msg = {'';        'Generates a list of random matrix sizes.'};case 'Build Program'    msg = {'';        'Creates a new M-file that will simulate the chain';        'multiply result selected from the results list.';        '';        'The program multiplies two matrices at a time, and';        'includes explicit usage of temporary matrices and';        're-use of output storage area when appropriate.'};endif isempty(msg),   msg = {'';      ['This is the ' tag '.']};end% Put up message box for help:%title = ['Help: ' tag];helpwin(msg,title);% Old message box:% hmsg = msgbox(msg,title, 'help','modal');% CenterFigOnFig(hfig, hmsg);% --------------------------------------------------------------function CenterFigOnFig(hfig,hmsg)% CenterFigOnFig Center hMsg figure on top of hFig figureset(hfig,'units','pix');figPos = get(hfig,'pos');figCtr = [figPos(1)+figPos(3)/2 figPos(2)+figPos(4)/2];set(hmsg,'units','pix');msgPos = get(hmsg,'position');msgCtr = [msgPos(1)+msgPos(3)/2 msgPos(2)+msgPos(4)/2];movePos = figCtr - msgCtr;new_msgPos = msgPos;new_msgPos(1:2) = msgPos(1:2) + movePos;set(hmsg,'Position',new_msgPos);return% --------------------------------------------------------------function install_context_help(hfig)ud = get(hfig,'userdata');cbh = @HelpGeneral;main = {'label','&What''s This?', 'callback',@HelpGeneral, 'parent'};setWTC(hfig,main, ud.h.Fig, 'Chain Multiplication GUI');setWTC(hfig,main, ud.h.ResultList, 'Result List');setWTC(hfig,main, [ud.h.MatrixSizes ud.h.MatrixSizesText], 'Matrix Sizes');setWTC(hfig,main, [ud.h.Status ud.h.ax_status], 'Status Bar');setWTC(hfig,main, ud.h.RandomButton, 'Random Matrices');setWTC(hfig,main, ud.h.BuildButton, 'Build Program');ud.Help.IsActive = 0;set(hfig,'userdata',ud);% --------------------------------------------------------------function setWTC(hfig,main,hItem,tagStr)% setWT Set the "What's This?" context menu and callback:hc = uicontextmenu('parent',hfig);uimenu(main{:},hc, 'tag', ['WT?' tagStr]);set(hItem,'uicontextmenu',hc);% ==================================================================================%ChainMultProg Print a MATLAB program that will simulate%   the optimal chain multiply result, including%   explicit usage of temporary matrices and possible%   re-use of output storage area.%%   EXAMPLE: The matrix multiplication chain representation%       {[4 5 -1] [3 -1 -2] [2 -2 -1] [1 -1 0]}%    is in the input argument field x.Best.ChainRep, and%    x.Best.tempOverOutputIdx = 2.  Based on this, the %    following program code is generated:%%    function y = mtrxmult(A,B,C,D,E)%    %MTRXMULT Compute y = A * (B * (C*(D*E)));%    %   using primitive 2-argument matrix multiplies.%    %%    %   This requires 496 flops and 8 temporary%    %   storage locations given the following matrix sizes:%    %    [5 8], [8 6], [6 8], [8 5], [5 8]%    %%    %   Note: the output is used for a temporary%    %   (intermediate computation) result.%    %%    %   Generated: 11-Jun-1999 17:29:17.%%    temp1 = D * E;%    temp2 = C * temp1;%    temp1 = B * temp2;%    y = A * temp1;%%    % [EOF] mtrxmult.m%% ==================================================================================function [yc,y] = ChainMultProg(x,idx)tempIdx  = x.All.Metrics(idx).tempOverOutputIdx;flops    = x.All.Metrics(idx).flopCount;mem      = x.All.Metrics(idx).temp_ele;chain     = x.All.Chain{idx};ppv       = x.All.ChainStr{idx};inputSize = prettyPrintSizes(x.Input.Sizes);inputCplx = mat2str(x.Input.Complexity);% Get # of variables and # temporaries in problem[numVars, numTemps, allVars, csvars] = generateVarLists(x,idx);% Write out header info:if any(x.Input.Complexity),   mstr = '(real) ';else   mstr = '';endy = {['function y = mtrxmult(' csvars ')'];     ['%MTRXMULT Compute ' ppv];     ['%    using primitive 2-argument matrix multiplies.'];     ['%    This requires ' num2str(flops) ' flops and ' ...             num2str(mem) ' temporary ' mstr];       ['%    storage elements given the following matrix sizes:']};        if any(x.Input.Complexity),     for i=1:length(x.Input.Sizes),        xi=x.Input.Sizes{i};        cplx=x.Input.Complexity(i);        if cplx, cplxStr='Complex'; else cplxStr='Real'; end        z = {['%    Input ' num2str(i) ': ' mat2str(xi)  ' (' cplxStr ')']};        y=[y;z];     end  else     % All purely real:     z = {['%    ' inputSize];          ['%    with all real inputs.']};     y=[y;z];  end % List of matrix sizes:% Time/date stampe for final portion of initial comment line:z = {'%';   ['%   Generated: ' datestr(now) '.']};y = [y; z];% Enumerate computational steps:k=numTemps+1;for i=1:length(chain),    x1 = chain{i}(1);    x2 = chain{i}(2);    x12 = chain{i}(3);    if (tempIdx>0) && (-x12 == tempIdx),        % Writing into a temp matrix that is being         %   stored in the output matrix area for optimization.        %        % Indicate that we're doing this:        comment='  % Using output for temp matrix';    else        comment = '';    end    y = [y; {[allVars{x12+k} ' = ' ...              allVars{x1+k} ' * ' allVars{x2+k} ';' comment]}];end% Write out program footer:y = [y;    {'';     '% [EOF] mtrxmult.m';	}];% Convert from cell to string:yc = char(y);% ------------------------------------------------------------function [numVars, numTemps, allVars, csvars] = generateVarLists(x,idx)% getVarListsnumVars  = 0;numTemps = 0;chain    = x.All.Chain{idx};tempIdx  = x.All.Metrics(idx).tempOverOutputIdx;tempList = {};for i=1:length(chain),    for j=1:3,        var = chain{i}(j);        if var>0,     % input var            numVars = max(numVars, var);        elseif var<0,  % temp var           	numTemps = max(numTemps,-var);        end	    endend% Comma-separated string of vars:varStr = char('A' + (0:numVars-1));csvars = [varStr; ones(1,numVars)*','];csvars = csvars(1:end-1);% Main Variable and Temp Variable cell-array lists:varList = cellstr(char('A' + (0:numVars-1)'))';for i=1:numTemps,    tempList{i}=sprintf('temp%d',i);end% Replace the specified temp variable name with the% output variable name, if the output was used in% place of this temporary storage area:if tempIdx>0,    tempList(tempIdx) = {'Y'};end	% Concatenate temp, output, and main vars into an% indexed list of all vars.%% order of variable names is [flipped_tempList output mainVars]% e.g., indices are [-N, -N+1, ..., -2, -1, 0, 1, 2, ..., M],% where N = # temp vars, 0=index of output var, M=# main vars%allVars = [fliplr(tempList) {'Y'} varList];% -----------------------------------------------------------function str = prettyPrintSizes(x)% prettyPrintSizes Print the chain multiply sizesN=length(x);str = '';for i=1:N,    if i<N, t=', '; else t=''; end   str = [str mat2str(x{i}) t];end%str=str(1:end-2);  % remove trailing comma/space% [EOF] chaingui.m

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -