%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% OtherFunctions_demo.m
%
% purpose: demo some useful functions in matlab
%
% written by tancy 05/08/2017
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


%% save matrix as dat and read dat in excel
m = [3 4; 5 6; 7 8];
csvwrite('csvlist.dat', m) % save m as dat file
csvread('csvlist.dat') % read dat file to matlab
% you can open *.dat in excel
% 1) start excel
% 2) file open 
% 3) select "All files"
% 4) select your *.dat file
% 5) text import wizard

%% print and publish

x = pi
fprintf('value of x: %d\n', x); % %d:signed integer

fprintf('value of x: %f\n', x); % %f:floating point

fprintf('value of x: %0.2f\n', x); % 2values after the decimal point


s = 'letter'
fprintf('value of s: %s\n', s); % %s: string of characters

s = 'letter'
fprintf('value of c: %c\n', c); % %c: single character


%% working with images
importedImage = imread('IMG_0974.jpg'); % import image
image(importedImage) % display image
importedImage90 = imrotate(importedImage, -90) % rotate image
image(importedImage90)



%% Basic statistics, sorting
x = [9 10 10 9 8 7 3 10 9 8 5 10];
xx = [9 10 10; 9 8 7; 3 10 9; 8 5 10]
min(x)
max(x)
max(max(x))

myvar = var(x) % variance
mystd1 = sqrt(myvar) % standard deviation
mystd2 = std(x) % standard deviation
mymode = mode(x) % the value that appears most frequently
                 % if no, return the smallest value 
mymedian = median(x)

%% Set operations
% union, intersect, unique, setdiff, setxor, unique

v1 = 2:6
v2 = 1:2:7

% The union function returns a vector that contains all the values 
% from the two input argument vectors, without repeating any.
union(v1,v2)

% The intersect function instead returns all the values 
% that can be found in both of the input argument vectors.
intersect(v1, v2)


% The setdiff function receives two vectors as input arguments, 
% and returns a vector consisting of all the values 
% that are contained in the first vector argument but not the second. 
setdiff(v1, v2)
setdiff(v2,v1)

% The function setxor receives two vectors as input arguments, 
% and returns a vector consisting of all the values from 
% the two vectors that are not in the inter- section of these two vectors.
setxor(v1,v2)

% unique returns all the unique values from a set argument
v3 = [1:5 3:6]
unique(v3)


%% sorting

vec = [85 70 100 95 80 91]
sort(vec)
sort(vec, 'descend')

mat = [4 6 2; 8 3 7; 9 7 1]
sort(mat,1) % sort by column
sort(mat,2) % sort by row














