Skip to main content

Posts

Showing posts with the label programming

Creating a Logfile for your project in Matlab

If you have a complicated project with many functions interconnected with each other, debugging could be a pain in the neck. To make it a bit more easier, I personally write "current status" of the code to a text file. Every time a specific event is caused, I write to the text file, along with the timestamp of the message. This helps me often, to pin point the mistake in my code. This is fairly simple thing to do. See the below function, write_log.m function write_log(msg) fid = fopen(fullfile(pwd, 'LogFile.txt' ), 'a' ); if fid == -1   error( 'Cannot open log file.' ); end fprintf(fid, '%s: %s\r\n' , datestr(now, 0), msg);   %this line could be changed to add more details to the message fclose(fid); end pwd stands for present working directory. I want to save the LogFile in the same directory as the current project. Every time the message, indicated by the variable msg here, is written to the text file, I precede...

Checking if two arrays are equal or not in Matlab

You might already know that to see if two variables are equal or not, we could use the == operator. But what about if you want to check two arrays or two structures are similar or not? In such a case a simple == doesn't work. In such a case, the function isequal helps us to achieve this. The usage is pretty simple, as you can see in the below examples... Example 1: A = zeros(2,2)+1e-10; B = zeros(2,2); check = isequal(A,B) A and B differ by a small fraction, but still the variable check shows the value "0" after running the snippet. Example 2: A = zeros(2,2); B = zeros(3,2); check = isequal(A,B) In the above case, both the arrays A and B have zero, but their size is different. Hence the answer, check shows "0". Example 3: A = struct( 'field1' ,0.05, 'field2' ,200); B = struct( 'field2' ,200, 'field1' ,0.05); check = isequal(A,B) The structures are declared in the first two lines. You can see that, f...

Find Execution Time In Matlab

MATLAB (matrix laboratory) is a multi-paradigm numerical computing environment and proprietary programming language developed by MathWorks. It still amazes me how easily scientific calculations can be done with the help of this tool. Sometimes you might want to know, how fast or slow is the piece of code you have written. This is very easy with matlab. The built-in function tic and toc can be used for this.  See the example below. tic  %add this statement just before the start of the code you want to check a=rand(100);  %create 100 by 100 random matrix. for i=1:10  %repeat 10 times     a=a*a;  %matrix multiplication end toc  %add this statement just after the end of the code you want to check The code is self explanatory. Running the code in Matlab 2016b, a message similar to the following will be shown on Command Window. Elapsed time is 0.045149 seconds. Pretty simple isn't it.  :)