{"id":925,"date":"2016-01-02T15:51:00","date_gmt":"2016-01-02T15:51:00","guid":{"rendered":"http:\/\/malemuk.com\/olofee\/?p=925"},"modified":"2016-01-04T15:37:29","modified_gmt":"2016-01-04T15:37:29","slug":"matlab-octave-tips","status":"publish","type":"post","link":"https:\/\/malemuk.com\/olofee\/matlab-octave-tips\/","title":{"rendered":"Matlab \/ Octave tips"},"content":{"rendered":"<p>Whenever I write [Octave] it means the stuff also works in Octave<\/p>\n<p><a href=\"#general\">General<\/a><br \/>\n<a href=\"#functions\">Functions<\/a><br \/>\n<a href=\"#io\">I\/O<\/a><br \/>\n<a href=\"#debug\">Debug<\/a><br \/>\n<a href=\"#dates\">Dates and times<\/a><br \/>\n<a href=\"#strings\">Strings<\/a><br \/>\n<a href=\"#plot\">Plot<\/a><br \/>\n<a href=\"#surffit\">Surface fitting<\/a><\/p>\n<h3 id=\"general\">General<\/h3>\n<p><strong>Entering long statements<\/strong><br \/>\nuse &#8216;&#8230;&#8217;<br \/>\n<code>all_data = textscan(fid, ['%n %n.%n.%n-%n.%n %n %s %n %s %d %s %d' ...<br \/>\n%s %d %s']);<br \/>\n<\/code><\/p>\n<p><strong>Output format [Octave]<\/strong><br \/>\n<code>format<\/code><br \/>\nMost used options:<br \/>\n<code>short<\/code><br \/>\n<code>long<\/code><br \/>\n<code>rat:<\/code> ratio<\/p>\n<p><strong>Variable type<\/strong><br \/>\n<code>whos myVar<\/code><\/p>\n<p><strong>Difference between &amp;&amp; and &amp;<\/strong><br \/>\n&amp;&amp; is a short-circuit version of the &amp; logical operator meaning when entering<br \/>\n<code>a &amp;&amp; b<\/code><br \/>\nMatlab first evaluates a and if it is wrong, terminates immediately without evaluating b<br \/>\nExample:<br \/>\n<code>if ( (x &gt; 0) &amp;&amp; (1\/x &lt;3) ) % 1\/x will never be evaluated with x = 0<\/code><\/p>\n<h3 id=\"functions\">Functions<\/h3>\n<p><strong>Making new functions visible<\/strong><br \/>\nIf you&#8217;re creating a new function with an editor that is not the Matlab editor, Matlab doesn&#8217;t detect it automatically. You solve this problem by typing<br \/>\n<code>clear functions<\/code><br \/>\nOf course the function file must be in your path, otherwise you can add it from the File menu<\/p>\n<p><strong>Syntax<\/strong><br \/>\n<code>function y = average(x)<\/code><br \/>\n<code>% AVERAGE Mean of vector elements.<\/code><br \/>\n<code>% only first comment line is printed when you type \"lookfor average\"<\/code><br \/>\n<code>% the other lines print when you type \"help average\"<\/code><br \/>\n<code>y = sum(x)\/length(x); % Actual computation<\/code><\/p>\n<p><code>function [Xout,Yout] = myFunc(x)<\/code><\/p>\n<p><strong>Number of arguments<\/strong><br \/>\nnargin: number of input arguments<br \/>\nnargout: number of output arguments<\/p>\n<p><strong>Variable number of input arguments<\/strong><br \/>\n<code>function testvar(x1, x2, varargin)<\/code><br \/>\nVarargin is a cell array. In the function body, access its cell values like this:<br \/>\n<code>varargin{i}(k)<\/code><\/p>\n<p><strong>Variable number of output arguments<\/strong><br \/>\n<code>function [varargout] = testvar2(arrayin)<\/code><br \/>\nVarargout is a cell array. Assign the cell values like this:<br \/>\n<code>varargout{i} = arrayin(k,:);<\/code><\/p>\n<p><strong>Anonymous functions<\/strong><br \/>\nDoes not require an M-file (perfect for defining functions in the command line)<br \/>\n<code>f = @(arglist) expression<\/code><br \/>\nexample:<br \/>\n<code>sqr = @(x) x.^2;<\/code><\/p>\n<h3 id=\"io\">I\/O<\/h3>\n<p><strong>Open a formatted text file<\/strong><br \/>\n<code>fid = fopen('file.dat','w')<\/code><br \/>\n<code>w<\/code>: write<br \/>\n<code>r<\/code>: read<br \/>\n<code>a<\/code>: append<br \/>\nreturns -1 if error<br \/>\nIf the file is a text file and you want to write to it, consider using &#8216;t&#8217; as an attribute if you want Windows line break<br \/>\nexample:<br \/>\n<code>fid = fopen('file.txt', 'wt')<\/code><\/p>\n<p><strong>Close file<\/strong><br \/>\n<code>fclose(fid)<\/code><br \/>\n<code>fclose('all') % closes all open files<\/code><\/p>\n<p><strong>Filename<\/strong><br \/>\n<code>[pathstr, name, ext, versn] = fileparts(filein);<\/code><br \/>\n<code>fileout = fullfile(pathstr, [name, '.out']);<\/code><br \/>\nWrite to formatted text file (line by line)<br \/>\n<code>fprintf(fid,'%2.4f\\n',x)<\/code><br \/>\nfid: 1 = stdout; 2 = stderr<br \/>\nomitting fid writes on the screen<br \/>\nd: integer<br \/>\nf: fixed point notation<br \/>\ne: exponential notation<br \/>\ng: same as f or e but insignificant zeros do not print<br \/>\ns: string of characters<br \/>\nc: character<br \/>\nRemember \\n for line break<\/p>\n<p><strong>fprintf tips<\/strong><br \/>\nPrinting strings and numbers together: it looks like you have to separate the printing of strings and numbers into distinct fprintf statements. Example:<br \/>\n<code>fprintf(fid, '%s', 'test ');<\/code><br \/>\n<code>fprintf(fid, '%d %d\\n', 10, 20); %printed on the same line as 'test <\/code>&#8216;<\/p>\n<p><strong>Write (numeric) matrices to text file<\/strong><br \/>\n<code>A = [1 2 3 4 ; 5 6 7 8];<\/code><br \/>\n<code>dlmwrite('my_data.out', A, ';')<\/code><br \/>\n&#8216;;&#8217; is the delimiter in my_data.out<br \/>\n&#8221; means no delimiter<br \/>\nNote: not necessary to open the file first<br \/>\nNote: use the following notation if you want Windows line break:<br \/>\n<code>dlmwrite('my_data.out', A, 'delimiter', ';', 'newline', 'pc')<\/code><br \/>\nTo decide the number precision use the &#8216;precision&#8217; attribute<br \/>\n<code>'precision', '%10.5f<\/code>&#8216;<\/p>\n<p><strong>Read ASCII delimited numeric data file<\/strong><br \/>\n<code>data = dlmread('myfile.dat');<\/code><br \/>\n<code>col1 = data(:,1);<\/code><\/p>\n<p><strong>Read from file containing numbers and strings<\/strong><br \/>\n<code>textscan<\/code><br \/>\nexample:<br \/>\nText file scan1.dat contains data in the following form:<br \/>\n<code>Sally Level1 12.34 45 1.23e10 inf NaN Yes<\/code><br \/>\n<code>Joe Level2 23.54 60 9e19 -inf 0.001 No<\/code><br \/>\n<code>Bill Level3 34.90 12 2e5 10 100 No<\/code><br \/>\nRead each column into a variable:<br \/>\n<code>fid = fopen('scan1.dat');<\/code><br \/>\n<code>C = textscan(fid, '%s %s %f32 %d8 %u %f %f %s');<\/code><br \/>\n<code>fclose(fid);<\/code><br \/>\nSpecifiers:<br \/>\n%s : string<br \/>\n%n : double<br \/>\n%d : int<br \/>\nNote that textscan returns a cell array. Therefore C{1} is the cell array containing the surnames &#8216;Sally&#8217;, &#8216;Joe&#8217; and &#8216;Bill&#8217;. C{1}(1) is the cell containing the string &#8216;Sally&#8217;. To convert this cell to a string (i.e. a character array), use the char function:<br \/>\n<code>sallyString = char(C{1}(1));<\/code><br \/>\nThe conversion is necessary e.g. if you want to write out the string using fprintf<\/p>\n<p><strong>Read file containing numbers and NaN<\/strong><br \/>\nexample:<br \/>\n<code>nc = 6; % number of columns of data in the input file<\/code><br \/>\n<code>fmt = repmat('%n', 1, nc);<\/code><br \/>\n<code>clear m;<\/code><br \/>\n<code>[m{1:nc}] = textread(filein, fmt);<\/code><br \/>\n<code>m = cat(2,m{:});<\/code><\/p>\n<p><strong>Delimiters (textscan and textread)<\/strong><br \/>\nDefault delimiter:<br \/>\n<code>' \\b\\t<\/code>&#8216;<br \/>\nTo use a different delimiter:<br \/>\n<code>C = textscan(fid, '%s %n', 'delimiter', '\\t');<\/code><br \/>\nIf a nondefault delimiter is specified, repeated delimiter characters are treated as separate delimiters. When using the default delimiter, repeated white-space characters are treated as a single delimiter.<\/p>\n<p><strong>Skipping fields (textscan and textread)<\/strong><br \/>\nUse asterisk: %*s instead of %s<br \/>\nParticularly handy when using textread where you can write the data directly into a list of variables<\/p>\n<p><strong>Error message<\/strong><br \/>\n<code>error('ERROR: wrong format');<\/code><\/p>\n<h3 id=\"debug\">Debug<\/h3>\n<p><strong>Debug a function that requires arguments<\/strong><br \/>\nOpen the function file in the editor<br \/>\n<code>edit function.m<\/code><br \/>\nRun the function from the command line<br \/>\n<code>function(x,y)<\/code><br \/>\nFor private functions:<br \/>\n<code>edit private\/privFunc.m<\/code><\/p>\n<p><strong>Commands<\/strong><br \/>\ndisp(val): display values while debugging (or simply val)<br \/>\nreturn : continue execution<br \/>\ndbstep : execute current line<br \/>\ndbquit : exit debugging<\/p>\n<p><strong>Measure time use<\/strong><br \/>\ntic, toc: measure the time elapsed between invoking<\/p>\n<h3 id=\"dates\">Dates and times<\/h3>\n<p><strong>Date formats<\/strong><br \/>\nDate string: 24-Apr-2006<br \/>\nSerial date number: 732791<br \/>\nDate vector: 2006 04 24 0 0 0<\/p>\n<p><strong>Conversion functions<\/strong><br \/>\ndatenum: convert to a serial date. In Octave 1 Jan 0000 is defined as day 1.<br \/>\ndatestr: convert to string representation of the date<br \/>\ndatevec: convert to a date vector<br \/>\nExample: the 265th day of year 2007 is<br \/>\n<code>datestr(datenum(2007,01,01) + 264)<\/code><\/p>\n<h3 id=\"strings\">Strings<\/h3>\n<p><strong>Concatenate strings<\/strong><br \/>\n<code>newString = [string1, string2, string3];<\/code><br \/>\nConvert an integer to a string<br \/>\n<code>newString = int2str(n);<\/code><\/p>\n<h3 id=\"plot\">Plot<\/h3>\n<p><strong>Plot with dates<\/strong><br \/>\nExample:<br \/>\n<code>plot(dates, y);<\/code><br \/>\n<code>datetick('x', 19);<\/code><br \/>\nNote1: dates must be a vector of serial dates (obtained with datenum)<br \/>\nNote2: 19 is one of a series of different formats that datetick can print the date into.<br \/>\nNote3: you might want to add &#8216;keepticks&#8217; as a third input argument in order to get a good tick repartition.<\/p>\n<p><strong>Subplots<\/strong><br \/>\nYou can plot several plots in the same window with the subplot command.<br \/>\nExample &#8211; drawing two plots next to each other:<br \/>\n<code>subplot(1,2,1);<\/code><br \/>\n<code>plot(x1,y1);<\/code><br \/>\n<code>subplot(1,2,2);<\/code><br \/>\n<code>plot(x2,y2);<\/code><br \/>\nThe two first figures indicate how the window is split, here 1 row and 2 columns while the third figure is the subwindow index.<\/p>\n<p><strong>Double axis graphs<\/strong><br \/>\nIn order to plot y1=f(x1) and y2=g(x2) with two Y-axes, copy the following lines:<br \/>\n<code>line(x1,y1,'Color','r');<\/code><br \/>\n<code>ax1 = gca;<\/code><br \/>\n<code>set(ax1,'XColor','r','YColor','r')<\/code><br \/>\n<code>ax2 = axes( 'Position',get(ax1,'Position'),. . . <\/code><br \/>\n<code> 'XAxisLocation','top',. . . <\/code><br \/>\n<code> 'YAxisLocation','right',. . . <\/code><br \/>\n<code> 'Color','none',. . . <\/code><br \/>\n<code> 'XColor','k','YColor','k'); <\/code><br \/>\n<code>line(x2,y2,'Color','k','Parent',ax2);<\/code><\/p>\n<p><strong>Plot several data sets<\/strong><br \/>\nEach time you call the <code>plot<\/code> command, it clears the plot window. If you want to keep the previous plot, you need to write<br \/>\n<code>hold all<\/code><br \/>\nbefore the first <code>plot<\/code> command and<br \/>\nRemember to write<br \/>\n<code>hold off<\/code><br \/>\nafter the last <code>plot<\/code> command. That way, the plot window will behave &#8220;normally&#8221; on the next <code>plot<\/code> call.<\/p>\n<p><strong>Grid<\/strong><br \/>\nExamples:<br \/>\n<code>set(gca, 'XGrid', 'on')<\/code><br \/>\n<code>set(gca, 'XMinorGrid', 'off')<\/code><\/p>\n<p><strong>Write text in the plot window<\/strong><br \/>\nThe easiest way is to use the <code>text<\/code> command:<br \/>\n<code>text(xpos, ypos, str)<\/code><br \/>\nCheck also out the <code>annotations<\/code> command<\/p>\n<p><strong>Fix X and Y limits<\/strong><br \/>\n<code>xlim([xmin xmax])<\/code><br \/>\n<code>ylim([ymin ymax])<\/code><\/p>\n<h3 id=\"surffit\">Surface fitting<\/h3>\n<p>You have a non-uniform collection of measured points (from total station, differential gps, etc.) and you want to plot an interpolated surface.<br \/>\nSuppose your points are stored as X, Y, Z.<br \/>\nFirst you build a uniform grid based on the extremities of the measured area:<br \/>\n<code>[Xm, Ym] = meshgrid (Xmin:s:Xmax, Ymin:s:Ymax);<\/code><br \/>\nwhere s is the grid size<br \/>\nThen you interpolate the surface at all the grid points:<br \/>\n<code>Zm = griddata (X, Y, Z, Xm, Ym);<\/code><br \/>\nEventually you may plot the surface:<br \/>\n<code>surf(Zi)<\/code><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Whenever I write [Octave] it means the stuff also works in Octave General Functions I\/O Debug Dates and times Strings Plot Surface fitting General Entering long statements use &#8216;&#8230;&#8217; all_data = textscan(fid, [&#8216;%n %n.%n.%n-%n.%n %n %s %n %s %d %s %d&#8217; &#8230; %s %d %s&#8217;]); Output format [Octave] format Most used options: short long rat: [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[14],"tags":[],"class_list":["post-925","post","type-post","status-publish","format-standard","hentry","category-computer-stuff"],"jetpack-related-posts":[{"id":910,"url":"https:\/\/malemuk.com\/olofee\/emacs-tips\/","url_meta":{"origin":925,"position":0},"title":"Emacs tips","date":"December 31, 2015","format":false,"excerpt":"Essential shortcuts M-: META key (ALT on most keyboards) C-: CONTROL key C-x C-f : open file C-x b : switch to buffer C-x k : kill buffer C-s : search text forward C-r : search text backward C-+ \/ C-- : Zoom in\/out C-space: mark set (start of the\u2026","rel":"nofollow","context":"In \"Computer stuff\"","img":{"src":"","width":0,"height":0},"classes":[]},{"id":886,"url":"https:\/\/malemuk.com\/olofee\/coastal-sea-ice-action-on-a-breakwater-in-a-microtidal-inlet-in-svalbard-phd\/","url_meta":{"origin":925,"position":1},"title":"Coastal-sea-ice action on a breakwater in a microtidal inlet in Svalbard (PhD)","date":"December 31, 2015","format":false,"excerpt":"PhD Thesis (PDF) Abstract Preface LaTeX source code of the thesis Writing statistics Defence Trial lecture Defence video Defence slideshow Defence slideshow with notes Questions from the opponents Articles 19th IAHR International Symposium on Ice (2008) Caline, F. and Barrault, S., 2008, Transmission of level ice stresses to the ice\u2026","rel":"nofollow","context":"In \"PhD\"","img":{"src":"","width":0,"height":0},"classes":[]},{"id":137,"url":"https:\/\/malemuk.com\/olofee\/alpine-configuration\/","url_meta":{"origin":925,"position":2},"title":"Alpine configuration","date":"October 23, 2010","format":false,"excerpt":"Alpine is to email software what Emacs is to text-editing software. I love it. First, create a collection list -- I think you may skip this part if you're using pop instead of imap: S L A Nickname: any nickname Server: my.server.net:port\/ssl\/user=my_username If you're not using ssl, write tls instead.\u2026","rel":"nofollow","context":"In \"Computer stuff\"","img":{"src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/malemuk.com\/olofee\/wp-json\/wp\/v2\/posts\/925","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/malemuk.com\/olofee\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/malemuk.com\/olofee\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/malemuk.com\/olofee\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/malemuk.com\/olofee\/wp-json\/wp\/v2\/comments?post=925"}],"version-history":[{"count":7,"href":"https:\/\/malemuk.com\/olofee\/wp-json\/wp\/v2\/posts\/925\/revisions"}],"predecessor-version":[{"id":955,"href":"https:\/\/malemuk.com\/olofee\/wp-json\/wp\/v2\/posts\/925\/revisions\/955"}],"wp:attachment":[{"href":"https:\/\/malemuk.com\/olofee\/wp-json\/wp\/v2\/media?parent=925"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/malemuk.com\/olofee\/wp-json\/wp\/v2\/categories?post=925"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/malemuk.com\/olofee\/wp-json\/wp\/v2\/tags?post=925"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}