Skip to content

Instantly share code, notes, and snippets.

@steven2358
Last active March 21, 2022 02:37
Show Gist options
  • Save steven2358/7578242 to your computer and use it in GitHub Desktop.
Save steven2358/7578242 to your computer and use it in GitHub Desktop.
Matlab Cheat sheet
% Matlab cheat sheet
% Author: Steven Van Vaerenbergh
% Last version: https://gist.github.com/steven2358/7578242
%% SYSTEM
% seed a random generator
seed = 1;
rng('default');
rng(seed);
% seed a random generator (explicit)
seed = 1;
s = RandStream('mt19937ar','Seed',seed);
RandStream.setGlobalStream(s);
% unique date string (time stamp)
datestr(now,30)
% get computer / host name
hostname = getenv('computername');
% check if a variable exists
a = exist('dataset','var');
% make folder if it does not exist
if exist('myfolder','dir') ~= 7
mkdir('myfolder');
end
% list all .txt files in a folder, and get filenames without extensions
BASE_DIR = 'C:\path\to\directory';
files = dir(fullfile(BASE_DIR,'*.txt'));
[~,files] = cellfun(@fileparts, {files.name}, 'UniformOutput',false);
% measure and store time since specified tic
aa = tic;
bb = toc(aa);
% swap variables
[c,a,b] = deal(a,b,c);
%% INTERFACE
% beep sound
soundsc(sin(1:1E4));
% beep sound (1 second, 440 Hz)
soundsc(sin(2*pi*440*(0:1/8192:1)));
% 10 progress dots
for n=1:N
if ~mod(n,floor(N/10)), fprintf('.'); end
end
fprintf('\n')
%% STRINGS
% replace a substring
strrep('This is a good example.', 'good', 'great');
% find a string in a cell array
strs = {'apples','oranges','bananas'};
ind = find(ismember(strs,'oranges'));
% find a substring (pattern) within a string
k = strfind(str, pattern);
% sum the digits of a number x
sum(num2str(x) - '0');
%% SIGNAL PROCSESING
% add SNR to signal x
sigpow = x'*x/length(x);
noisepow = 10^(-SNR/10)*sigpow;
%% FIGURES
% legend location
legend('mytitle','Location','SW');
% remove legend box
legend boxoff
% set position and size of figure
set(gcf,'Position',[500 400 400 150])
% get standard colors
colors = get(gcf,'DefaultAxesColorOrder');
% set font and font size
set(gca, 'FontName', 'Times New Roman');
set(gca, 'FontSize', 11);
% set axis limits
axis([x1 x2 y1 y2])
% change only one limit of an axis
xlim([0 1])
% alternative way to change axis
xlim = get(gca,'XLim');
ylim = get(gca,'YLim');
axis([xlim(1) 0 ylim(1) ylim(2)])
% set the x-axis to logarithmic scale
set(gca,'XScale','log');
% expand figure axes
f = gcf;
style = hgexport('factorystyle'); style.Bounds = 'tight';
hgexport(f,'-clipboard',style,'applystyle', true);
drawnow;
% print PNG figure
print('-dpng','-r300',myfilename);
% print color EPS figure
print('-depsc2','-r300',myfilename);
% fix line style (using
% http://www.mathworks.com/matlabcentral/fileexchange/17928-fixpslinestyle)
fixPSlinestyle([myfilename '.eps'])
% formatted text box. Extra arguments: FontName, FontSize, FontWeight
axes('position',[0 0 1 1],'visible','off')
text(0.5,0.6,'mytext')
% setting ticks and labels
set(gca,'XTick',0:10:100)
set(gca,'XTickLabel',{'A','B'})
% change plot interpreter to tex or latex
ylabel('$\alpha$','Interpreter','LaTex')
% Greek letters in tick labels
str=['p/2';'p']; % \pi/2, \pi
set(gca,'xticklabel',str,'fontname','symbol')
% change aspect ratios for different axes
set(gca,'dataaspectratio',[1,1,.5]);
% save figure in .fig format
saveas(gcf, 'path', 'fig');
% transparant bg
set(gcf, 'InvertHardcopy', 'off')
% extract data from plot
h = findobj(gca,'Type','line');
x=get(h,'Xdata');
y=get(h,'Ydata');
% get standard colors
colors = get(0,'DefaultAxesColorOrder');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment