Search notes

Search titles and full post content.

    ← All notes

    MATLAB Tips

    MatLab Code

    General Programming Tips

    1. Compute the running time of a function all

      1
      tic; fft(rand(500)); disp( [’it takes ’ num2str(toc) ’s.’] );
    2. Locate the indice of minimum value in a matrice

      1
      2
      [M,I]         = min(objMatrice(:)); % 'objMatrice' is the objective matrix
      [Irow,Icol] = ind2sub(size(objMatrice),I);
    1. Sort ascending filenames based on number

      1
      2
      3
      4
      5
      sFile = dir([dir1 'temp*.mat']);
      %%% sort ascending filenames based on Number
      [~, reindex] = ...
      sort(str2double(regexp( {sFile.name}, '\d+', 'match', 'once' )));
      sFile = sFile(reindex) ;
    2. Writing/Reading to a text file a list of 3-uplets.

      1
      2
      3
      4
      5
      6
      % A is a matrix with 3 rows.
      fid = fopen(filename,’wt’);
      fprintf(fid, ’%f %f %f\n’, A);
      fclose(fid); % Retrieving the values back from file to matrix B.
      fid = fopen(filename,’r’);
      [B,cnt] = fscanf(fid,’%f %f %f’);
    3. Create a graphical waitbar

      1
      2
      3
      4
      5
      6
      7
      n = 100;
      h = waitbar(0,’Waiting ...’);
      for i=1:n
      waitbar(i/n);
      % here perform some stuff
      end
      close(h);
    4. Loading issue

      1
      2
      3
      4
      5
      6
      try
      load('xxx.mat') % x
      catch
      datatemp = matfile('xxx.mat'); % x
      data = datatemp.x;
      end

    Sub-function Tricks

    1. Create a sub-function that takes optional arguments in a struct

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      function y = f(x,options)
      % parse the struct
      if nargin<2
      options.null = 0; % force creation of options
      end
      if isfield(options, ’a’)
      options.a = 1; % default value
      end
      a = options.a;
      if isfield(options, ’b’)
      options.b = 1; % default value
      end
      b = options.b;
      % Here the body of the function ...

      note: nargin returns the number of function input arguments given in the call to the currently executing function.

    2. Use varargin in function e.g. as following. A single function to generate two-dimensional (2D) line graphs, avoiding a long list of code for the generation of each graphic.

      PlotSet generates 2D plots, including multiple plots on a page. This code processes varargin as
      parameter pairs to set options. This makes it easy to expand the options. You can look for more information in the following book.

      Paluszek, M., and S. Thomas. MATLAB Machine Learning. Apress, 2016. https://books.google.com.au/books?id=jy75vQAACAAJ.

    3. Write a function fun(a,b,c) that can take an arbitrary number of arguments

      1
      2
      3
      4
      5
      function fun(args)
      default_values = {0.1246,1.2346,8.7643};
      args_present = cellfun(@isempty,args);
      default_values(args_present) = args(args_present);
      [a b c] = deal(default_values);
    4. Load a variable from a .mat file and then place that variable inside a structure with the same name

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      % Load the variable
      loadedData = load('myData.mat'); % This loads the data into a structure

      % Extract field names from the loaded data
      fieldNames = fieldnames(loadedData);

      % Loop through each variable and assign it to a new structure with the same name
      for k = 1:length(fieldNames)
      varName = fieldNames{k};
      dataStruct.(varName) = loadedData.(varName);
      end
      % Now dataStruct has fields corresponding to the variables loaded from the .mat file

    Mathematical Tips

    1. Generate n points x sampled uniformly at random on a sphere.

      1
      2
      3
      4
      5
      6
      % tensor product gaussian is isotropic
      x = randn(3,n);
      d = sqrt( x(1,:).ˆ2+x(2,:).ˆ2+x(2,:).ˆ2 );
      x(1,:) = x(1,:)./d;
      x(2,:) = x(2,:)./d;
      x(3,:) = x(3,:)./d;
    2. Keep only the n biggest coefficients of a signal x (set the others to 0).

      1
      [tmp,I] = sort(abs(x(:))); x( I(1:end-n) ) = 0;

    Plotting

    1. Draw a 3D sphere.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      p = 20; % precision
      t = 0:1/(p-1):1;
      [th,ph] = meshgrid( t*pi,t*2*pi );
      x = cos(th);
      y = sin(th).*cos(ph);
      z = sin(th).*sin(ph);
      surf(x,y,z, z.*0);
      % some pretty rendering options
      shading interp; lighting gouraud;
      camlight infinite; axis square; axis off;
    2. Edit legend

      1
      2
      3
      4
      5
      6
      7
      8
      9
      [hhLeg,labelhandles] = legend(ax(1),htext,'location','NorthEast'...
      ,'box','off','Interpreter','LaTex','FontSize',fS);
      % hhLeg.ItemTokenSize =[20 18];
      labelhandles(5).LineStyle = '-';
      labelhandles(4).XData = [0.24 0.37];
      labelhandles(5).XData = labelhandles(4).XData;
      labelhandles(4).YData = labelhandles(4).YData + 0.07;
      labelhandles(5).YData = labelhandles(4).YData - 0.14;
      labelhandles(5).Color = col2(1,:);
    3. Copy all properties for Axes

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      ax(2) = axes('Position',ax(1).Position ...
      ,'OuterPosition',ax(1).OuterPosition ...
      ,'InnerPosition',ax(1).InnerPosition ...
      ,'ActivePositionProperty',ax(1).ActivePositionProperty...
      ,'ALim',ax(1).ALim...
      ,'ALimMode',ax(1).ALimMode...
      ,'color','none'...
      ,'xtick',[],'ytick',[],'ztick',[]...
      ,'xcolor','none','ycolor','none','zcolor','none'...
      ,'Projection','perspective'...
      ,'CameraPosition',ax(1).CameraPosition ...
      ,'CameraPositionMode',ax(1).CameraPositionMode...
      ,'CameraTarget',ax(1).CameraTarget...
      ,'CameraTargetMode',ax(1).CameraTargetMode...
      ,'CameraUpVector',ax(1).CameraUpVector...
      ,'CameraUpVectorMode',ax(1).CameraUpVectorMode...
      ,'CameraViewAngle',ax(1).CameraViewAngle...
      ,'CameraViewAngleMode',ax(1).CameraViewAngleMode...
      ,'DataAspectRatio',ax(1).DataAspectRatio...
      ,'DataAspectRatioMode',ax(1).DataAspectRatioMode...
      );

      % copyaxes(ax(1),ax(2))
    4. set handle in a figure invisible

      1
      2
      3
      4
      5
      6
      7
      set(findall(hFig,'Type','arrow'),'visible','off')
      set(findall(hFig,'Type','textbox'),'visible','off')
      set(findall(hFig,'Type','axes'),'visible','off')
      set(findall(hFig,'Type','surf'),'visible','off')
      set(findall(hFig,'Type','patch'),'visible','off')
      set(findall(hFig,'Type','Line'),'visible','off')
      set(findall(hFig,'Type','contour'),'visible','off')
    5. plot at a specific plane

      1
      2
      3
      4
      tt = hgtransform(ax(2)); % establish plane 
      % X-axis rotation matrix and Z-axis translation matrix
      Rz = makehgtform('translate',[0 y(end) 0],'xrotate',1/2*pi,'yrotate',-1/2*pi);
      set(tt,'Matrix',Rz);
    6. Two axes in one figure

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      ax(1) = axes('box','on');hold(ax(1),'on')
      ax(2) = axes('Position',ax(1).Position ...
      ,'color','none'...
      ,'yAxisLocation','right'...
      ,'box','off'...
      ,'xTick',[]...
      ...,'ytickLabel',[]...
      ,'ycolor',[0.5 0.5 0.5]...
      );
      hold(ax(2),'on')
    7. Iso-contours

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      [cContourMap,hContourMap] = contourf(gca,XXAB',YYAB',ZZAB');
      set(hContourMap,'linestyle','none')
      yclimColorbar = [0 1];
      ytickColorbar = 0:0.2:1;
      colLevelist = 0:0.1:1;
      hContourMap.LevelList = colLevelist;
      set(gca,'clim',yclimColorbar)
      hColorbar = colorbar(gca);
      titleindex = 'title';
      set(get(hColorbar1,'title'),'string'...
      ,titleindex...
      ,'FontSize',11 ...
      ,'interpreter','LaTex'...
      ,'FontName','Times New Roman' ...
      )
      set(hColorbar1...
      ,'ylim',yclimColorbar...
      ...,'ylim',[0 4]...
      ,'ytick',ytickColorbar...
      ,'Location','southoutside'...
      ... ,'AxisLocation','out'...
      ,'Units','Normalized'...
      ...,'Position',[0.1 0.2 0.6 0.03] ...
      ,'FontSize',11 ...
      ,'FontName','Times New Roman' ...
      )

    8. Circular legend for contour lines

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      hFigPos = hFig.Position;
      xCentre = 0.47;
      yCentre = 0.18;
      coll1 = flipud(coll1);
      radius = 0.07;
      radii = linspace(0.01,radius,round(size(coll1,1)/2));
      for iR = 1:length(radii)
      annotation(hFig,'ellipse', [xCentre - radii(iR)/2, yCentre - radii(iR)*hFigPos(3)/hFigPos(4)/2 ...
      , radii(iR), radii(iR)*hFigPos(3)/hFigPos(4)], ...
      'Color', coll1(iR,:), 'LineWidth', 1);
      end
    9. Generate gif

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      % Video to GIF Synchronization Script
      % Created by: Yu Xia
      % Location: Melbourne, Australia
      % Date: 2024.08.09

      % Initialize video file and reader
      videoFile = 'videoName.mp4';
      videoObj = VideoReader(videoFile);

      % Set output filename
      outputFilename = 'synchronized_animation.gif';

      % Get total number of frames
      numFrames = videoObj.NumFrames;

      % Create figure and axes
      hFig = figure('Color', 'white', 'Units', 'normalized', 'Position', [0.1 0.1 0.8 0.8]);
      ax(1) = axes('Parent', hFig, 'Position', [0.05 0.1 0.4 0.4], 'Box', 'on', 'Color', 'white');
      ax(2) = axes('Parent', hFig, 'Position', [0.5 0.1 0.4 0.4], 'Box', 'on', 'Color', 'white');

      % Hold axes for plotting
      hold(ax(1), 'on');
      hold(ax(2), 'on');

      % Configure second axes
      set(ax(2), 'XLim', [-60 60], 'YLim', [-9 -4], 'TickLength', [0.02 0.02], ...
      'XTick', -60:20:60, 'YTick', -9:1:-4, 'Box', 'on', 'XTickLabelRotation', 0);

      % Set labels for second axes
      xlabel(ax(2), '$\alpha$ ($^\circ$)', 'Interpreter', 'LaTeX', 'FontSize', 12);
      ylabel(ax(2), '$E$ (V)', 'Interpreter', 'LaTeX', 'FontSize', 12);

      % Process video frames
      for iAlpha = 1:numFrames
      % Read video frame
      videoFrame = read(videoObj, iAlpha);
      currentTime = videoObj.CurrentTime;

      % Display video frame
      imshow(videoFrame, 'Parent', ax(1));

      % Plot data on second axes (replace 'xx' with actual data)
      plot(ax(2), xx, xx, 'k', 'MarkerSize', 4, 'Color', col2, 'LineWidth', 1.3, 'LineStyle', '-');

      % Capture frame and convert to image
      frame = getframe(hFig);
      im = frame2im(frame);

      % Write frame to GIF
      if iAlpha == 1
      [imind, cm] = rgb2ind(im, 256, 'nodither');
      imwrite(imind, cm, outputFilename, 'gif', 'LoopCount', inf, 'DelayTime', 0.1);
      else
      imind = rgb2ind(im, cm, 'nodither');
      imwrite(imind, cm, outputFilename, 'gif', 'WriteMode', 'append', 'DelayTime', 0.1);
      end
      end

      % Close figure
      close(hFig);

      disp('GIF creation complete.');
    10. Store section title into a tiff image

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    function metaTiffEdit(printName, sectionName)

    if nargin < 2 || isempty(sectionName)
    % Automatically retrieve section title if sectionName is not provided
    sectionName = getSectionTitleFromActiveScript();
    end

    % Open the TIFF file for editing
    fileID = Tiff([printName '.tif'], 'r+');

    % Get the current script directory and file details
    [currentDir, Filename, ext] = fileparts(matlab.desktop.editor.getActiveFilename);
    fprintf('current working directory: %s\n', currentDir);

    % Prepare metadata string
    metaData = sprintf('%s%s%s', currentDir, Filename, ext);

    % Set the TIFF tags
    fileID.setTag('Artist', metaData);
    % fileID.setTag('Copyright', 'Your Copyright Info');
    % fileID.setTag('DateTime', datestr(now, 31)); % Using current date and time
    % fileID.setTag('DocumentName', 'Document Name');

    fileID.setTag("ImageDescription", sectionName);
    fileID.close;
    end

    function sectionTitle = getSectionTitleFromActiveScript()
    % Get the active editor object
    activeEditor = matlab.desktop.editor.getActive;

    % Get the position of the cursor
    cursorPosition = activeEditor.Selection(1);

    % Retrieve the content of the script as lines
    % lines = strsplit(activeEditor.Text, '\n');
    lines = splitlines(activeEditor.Text);

    % Initialize sectionTitle to an empty string
    sectionTitle = '';

    numLines = length(lines);
    cursorPosition = min(cursorPosition,numLines);


    % Find the most recent section title, starting from the current line
    for i = cursorPosition:-1:1
    if startsWith(strtrim(lines{i}), '%%') && ...
    ~startsWith(strtrim(lines{i}), '%%%')
    sectionTitle = strtrim(lines{i});
    break;
    end
    end

    % If no section title was found, default to 'Untitled Section'
    if isempty(sectionTitle)
    sectionTitle = 'Untitled Section';
    end

    % Optionally, remove the '%%' characters from the section title
    sectionTitle = strrep(sectionTitle, '%%', '');
    end

    Drawing Technique

    1
    2
    3
    4
    5
    6