MATLAB Tips
General Programming Tips
Compute the running time of a function all
1
tic; fft(rand(500)); disp( [’it takes ’ num2str(toc) ’s.’] );
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);
Sort ascending filenames based on number
1
2
3
4
5sFile = dir([dir1 'temp*.mat']);
%%% sort ascending filenames based on Number
[~, reindex] = ...
sort(str2double(regexp( {sFile.name}, '\d+', 'match', 'once' )));
sFile = sFile(reindex) ;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’);Create a graphical waitbar
1
2
3
4
5
6
7n = 100;
h = waitbar(0,’Waiting ...’);
for i=1:n
waitbar(i/n);
% here perform some stuff
end
close(h);Loading issue
1
2
3
4
5
6try
load('xxx.mat') % x
catch
datatemp = matfile('xxx.mat'); % x
data = datatemp.x;
end
Sub-function Tricks
Create a sub-function that takes optional arguments in a struct
1
2
3
4
5
6
7
8
9
10
11
12
13
14function 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.
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.
Write a function fun(a,b,c) that can take an arbitrary number of arguments
1
2
3
4
5function 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);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
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;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
Draw a 3D sphere.
1
2
3
4
5
6
7
8
9
10p = 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;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,:);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
23ax(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))set handle in a figure invisible
1
2
3
4
5
6
7set(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')plot at a specific plane
1
2
3
4tt = 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);Two axes in one figure
1
2
3
4
5
6
7
8
9
10ax(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')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' ...
)Circular legend for contour lines
1
2
3
4
5
6
7
8
9
10
11hFigPos = 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);
endGenerate 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.');Store section title into a tiff image
1 | function metaTiffEdit(printName, sectionName) |
Drawing Technique
1 |