home

Welcome to Matlab/Octave/FreeMat Cheat Sheet for PHY408/493/495
code format="matlab" % always use 'help command' to get detailed information on command usage. % Many commands can take in arguments of scalar, vector and matrix. % for more questions, click on 'Need Help?' Page.

% system % clear workspace and close all figures, use at the start of m-script clear all; close all; % clear workspace memories, including all defined variables and functions clc;

% vectors, arrays and matrices % define vectors avector=[10 20 50]; bvector=[]; % empty array

% if you know the start,end and interval of an evenly-spaced vector t=tstart:dt:tend; % if you know the start, end and length of the evenly-spaced vector t=linspace(tstart,tend,nt); % initialize a vector/matrix m=zeros(4,3); n=ones(size(t));

% assign vectors/matrices s = s_data(:,1); s_data(:,3) = s.*han;

% concatenate vectors/matrices t=[t1(1:nt),t2]; % concatenate strings title_string=strcat('f = ', num2str(fval));

% loop over elements of a vector: nt_vector=[10,25,30,45,50]; for i = 1 : length(nt_vector) nt=nt_vector(i); % calculate num bvector=[bvector num]; end

% matrix manipulation z = dot(x(1:10),y(1:10)) % dot product of two vectors

% functions applied to scalar, vector, array and matrix --- max_n = max(0, n) % similarly min nf = floor(f) % similarly ceil, round [a,b] = size(m); % dimension of matrix c=transpose(b); % or c=b' for real matrix n=length(x); % length of vector

% PLOTTING % plot multiple curves on one figure figure(1); plot(t,g,'rx') hold on; plot(tt,gg,'.'); % or plot(t,g,'rx',tt,gg,'.')

% subplots figure(2) subplot(2,2,1); plot(x,y); subplot(2,2,2); plot(x,z); % ...

% plot misc title('Name of figure'); xlabel('time (s)'); ylabel('displacement (m)'); legend('Data','Synthetics'); % if you plotted two lines

% fine-tuning (to make your axes and lines more prominent) % put before any plotting commands set(0,'Defaulttextfontsize',18); set(0,'Defaultaxesfontsize',15) set(0,'DefaultAxesLineWidth',1) set(0,'Defaultlinelinewidth',2); set(0,'DefaultlineMarkerSize',2);

% read and write ASCII files % read simple numerical data sheet s=load('adjoint.txt'); s1=s(:,1); dt=s(2,1)-s(1,1); % differentiate seismogram s3=diff(s(:,2))/dt; s3=[s3;s3(end)]; % read ASCII delineated file M = dlmread('mydata.txt','\t'); % read general ASCII data sheet [sta,lat,lon,ev,x,y,t]=textread('loc_dat_1','%s %f %f %f %f %f %f ','headerlines',2);

% write to ascii file, the corresponding matrix should be 2xn corresponding to 2 format entries fid = fopen('out.txt','w'); fprintf(fid,'%6.2f %12.8f\n',[s1';s3']); % the variable list has to be two rows and n columns fclose(fid); % printing  (instead of 'save as' from the menu) print -djpeg -r200 my-figure.jpg

% tricks % to show more significant digits of numerical values format long code