Monday, September 14, 2020

Tip when reading data from file

When I read data from a file in Matlab, I sometimes read the wrong file because files have the same name but different paths and I want to read the latest file. If you print the file date/time to Matlab's command window, you will get a visual indication which can alert you if you read an older file with the same name. You can use the following two lines to print file date:
fileInfo = dir(fileName);
fprintf("File date: %s\n", fileInfo.date);

Friday, September 11, 2020

Printing all permutations of a string

You can use the following C code to print all two character permutations (with repetition allowed) of a string:

If you would like to print three character permutations, you have to add another for loop:

As you can see, this is not generalizable because you have to keep adding or deleting for loops manually. Also notice that with each loop, the p[] index is increased by one. We could use this fact to write a recursive function that could handle all character permutations:

This is a nice example of first writing the simple cases, seeing a pattern and reaching the general case, i.e. inductive reasoning.