Reduction of time for the code of sorting RGB and Depth images according to timestamp values
You are reading in an image and then writing it back out again without making any changes. If the purpose is to copy the file, you are better off directly copying the file. You can use the function copyfile for that.



The code is fairly readable. There are some improvements you can make:


filePattern = fullfile(depth_img, '*.timestamp');
file = dir(filePattern);

filePattern2 = fullfile(color_img, '*.timestamp');
file2 = dir(filePattern2);

filePattern3 = fullfile(depth_img, '*.bmp');
file3 = dir(filePattern3);

filePattern4 = fullfile(Openpose, '*.png');
file4 = dir(filePattern4);



The four filePatternN variables are never used again. Why use four different variables, rather than repeat the same name? Why not omit the temporary variable and put these into single lines?

file = dir(fullfile(depth_img, '*.timestamp'));


Next, you have two identical loops, one reads from file, one from file2. One writes to A, one to B. Why not make this into a function? You can write local functions at the end of your M-file. You'd simplify this bit to:

A = get_time_stamps(file);
B = get_time_stamps(file2);


Another difference between these two loops is that one uses fileID and one uses fileID2. There is again no need to use two different names for local variables that you don't use outside the loop.

You can improve your code by making A and B numeric arrays rather than cell arrays:

tmp = textscan(fileID,'%d64');
A(k) = tmp{1};


Be sure to preallocate the arrays! 

Next you have again two large blocks of mostly repeated code. if length(file2) &lt;= length(file). You could put this into a function and call it do_stuff(file,file2) or do_stuff(file2,file) depending on which of the two is larger. But really, this might not be necessary at all with some better logic.

To find which time stamps are closest to each other, you don't need a O(n2) algorithm. You could instead sort the two arrays of time stamps, and walk through them one by one. The algorithm might be slightly more complex, but you wouldn't need to duplicate the code.

The other alternative is to use vectorized processing to do the O(n2) computation without using loops at all. But in modern versions of MATLAB, loops are not so slow any more, so this is not something you should be worrying about anyway. The way to speed up this loop is to preallocate the array C.

You can also simplify it by writing C{m,k} = abs(A{k,1} - B{m,1});, and removing the if statement.