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

12. normalize a vector of points belonging to the interval [a,b]

a=10;
b=20;
v=rand(1,10)*5+1
n_data = a+(b-a)*(v-min(v))/( max(v)-min(v))

13. Correlation between two vectors

Given:

A_1 = [10 200 7 150]';
A_2 = [0.001 0.450 0.007 0.200]';

There are tools to simply compute correlation, most obviously corr:

corr(A_1, A_2);  %Returns 0.956766573975184  (Requires stats toolbox)

You can also use base Matlab’s corrcoef function, like this:

M = corrcoef([A_1 A_2]):  %Returns [1 0.956766573975185; 0.956766573975185 1];
M(2,1);  %Returns 0.956766573975184 

Which is closely related to the cov function:

cov([condition(A_1) condition(A_2)]);

14. Convert java.util.ArrayList to MATLAB array

% create arraylist

import java.util.ArrayList

val_list = java.util.ArrayList();

for i = 1:length(data)

val_list.add(data(i))

end

% convert to matlab array

cell2mat(val_list.toArray.cell)

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