Some useful MATLAB code snippets

[ More to be added soon …]

1. Find all subfolders under a directory


d = dir(pathFolder);
 isub = [d(:).isdir]; %# returns logical vector
 nameFolds = {d(isub).name}';
 %You can then remove . and ..
 nameFolds(ismember(nameFolds,{'.','..'})) = [];

2. Find index of cells containing my string


IndexC = strfind(C, 'bla');
 Index = find(not(cellfun('isempty', IndexC)));

3. Read gif image correctly

You need to get and use the colormap from the file:


[X,map] = imread('im0004.gif');
 imshow(X,map)

4. To convert ‘gif’ to other format

        if strcmp(ext, 'gif') == 1
            [im,map] = imread(fullfile(src, dir_list{j}, files(i).name));
            im = ind2rgb(im,map); % convert gif to rgb format using colormap
        else
            im  = imread(fullfile(src, dir_list{j}, files(i).name));
        end
        [~,name,~] = fileparts(files(i).name);
        imwrite(im, fullfile(src, dir_list{j}, [name '.jpg']));

5. Counting frequency of occurrence in matrix

x =[
22 23 24 23
24 23 24 22
22 23 23 23];
a = unique(x);
out = [a,histc(x(:),a)];

6. count occurrences of string in a single cell array (How many times a string appear)

xx = {'computer', 'car', 'computer', 'bus', 'tree', 'car'}
a=unique(xx,'stable')
b=cellfun(@(x) sum(ismember(xx,x)),a,'un',0)

7. Add a vector as column to cell array

 C = {'a' 'b' 'c' 'd'
      'e' 'f' 'g' 'h'
      'i' 'j' 'k' 'l'
      'm' 'n' 'o' 'p'}
 a=[1 2 3 4]
 out=[num2cell(a); C]

%or

 out=[num2cell(a')  C]

% for third case

 out=C(:)'

%or

 out=reshape(C,1,[])

8. Global figure title for a group of subplots

suptitle(strrep(fnames{f}, '_', '-'));

9. Save maximized figure

set(fig, 'Position', get(0,'Screensize')); % Maximize figure
set(fig, 'PaperPositionMode', 'auto');
saveas(fig, [dst fnames{f} '_subrange_plot.png']);

10. Plot points on image with serial numbers.

% apply data labels to each point in a scatter plot
% x = 1:10; y = 1:10; scatter(x,y);
% a = [1:10]'; b = num2str(a); c = cellstr(b);
% dx = 0.1; dy = 0.1; % displacement so the text does not overlay the data points
% text(x+dx, y+dy, c);

11. calculate the execution time of program

tic
yourCode
timeElapsed = toc

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s