Thursday, 19 December 2013

How to set the size of the texts and axes indices in Matlab plot?

0.8. How to check the properties that are accessible to the user?

set(gcf) % this command lists all the properties

0.9. Setting default font name for axis and texts in figure


set(0,'defaultAxesFontName', 'arial')
set(0,'defaultTextFontName', 'arial')


1. To set the properties of ALL that have the property 'fontsize' in figure, use:

set(findall(gcf, '-property', 'FontSize'), 'FontSize', 12, 'fontWeight', 'normal')

% findall returns all the children which have the property 'fontsize'.
% This command will set size of the labels, legends, title, and axis indices

2. To set only the text part (this excludes the numbers (indices))

set(findall(gcf,'Type','text'),'FontSize',14);

%How to change the font name

set(findall(gcf,'Type','text'),'FontName','Arial');
%or
set(findall(gcf,'Type','text'),'FontName','Times New Roman');  


3. To set the line width of all the 'lines' in a plot

set(findall(gcf,'Type','line'),'linewidth',2)

3.1 To set the MarkerSize, MarkerEdgeColor, MarkerFaceColor in a plot
    set(findall(gcf,'Type','line'),'MarkerSize',10)
    set(findall(gcf,'Type','line'),'MarkerEdgeColor','r')
    set(findall(gcf,'Type','line'),'MarkerFaceColor','b')


%Above commands work for subplots as well

4. To control only the axes indices and legend when we have subplots

set(findall(gcf,'type','axes'),'fontsize',20);
%or
axes('FontSize',12)


% How to reduce the space between the subplots? 
Explanation is given in this link.
Example is given below:

h2 = subplot(312), plot(freqBins,acfDelay,'-o')

p  = get(h2, 'pos'); % returns [left, bottom, width, height] = [Pos(x,y), size(x,y)]

ylim([-30 40]);
set(gca,'ytick',[-30:15:30])
box off;
ylabel('Delay (m)');
set(gca,'xticklabel','')
grid on

p(2) = p(2) + 0.05;
set(h2, 'pos', p);



5. To apply these common settings to multiple figures:
When there are multiple figures, instead of having these commands for every plot, after generating all the plots use 'for loop' to apply these common settings to all the figures.

Use 'figure(n)' to select the figure to which the settings should be applied. This reduces the code size significantly and allows to easily modify all the figures at one place.



Example:

%% Beautifying figures


%To set the default font for texts and axes in figures.
set(0,'defaultAxesFontName', 'arial')
set(0,'defaultTextFontName', 'arial')

for figNum = 1:1:2
    figure(figNum);
    %To set the axes indices font
    set(findall(gcf,'type','axes'),'fontsize',12);

    %To set the line width
    set(findall(gcf,'Type','line'),'linewidth',2)



%To set the MarkerSize, MarkerEdgeColor, MarkerFaceColor in a plot
    set(findall(gcf,'Type','line'),'MarkerSize',10)
    set(findall(gcf,'Type','line'),'MarkerEdgeColor','r')
    set(findall(gcf,'Type','line'),'MarkerFaceColor','b')


    %To set the fontsize of the text inside the plot (legend and other text)
    set(findall(gcf,'Type','text'),'FontSize',12);
 
    %Set the Font name
    set(findall(gcf,'Type','text'),'FontName','arial');
 
    %To adjust size of the figure
    set(gcf,'Units','centimeters');
    figSize = [20 15]; %width x height
    set(gcf,'Position',[5 5 figSize]); % [position , size]
 
    %Adding legends - split into two columns. 'columnlegend' is from
    %FileExchange
    columnlegend(2, legArray,'location','northEast','boxoff') ; % previous set commands remove this effect. %Hence, used after those
 
    box off;
    grid on;
 
    %Saving the figure in meta file. This format allows us to edit the
    %figure in MS-word.
    saveas(gcf,'test1454523.emf','emf')
end

Saturday, 7 December 2013

How to read from and write to a binary and text (ASCII) file in Matlab?

1. Here is the example for binary:

% Clear screen, clear workspace, and close all figures
clc;
clear all;
close all;

% Path and file name
% Read file
fReadName = 'ReadDataFile.bin'; % file from the current working directory

% Write file
fWriteName = 'WriteDataFile.bin';  % file to be written into the current working directory

% Open the file in read mode
 fidRead = fopen(fReadName,'rb');

 % Open the file in write mode
fidWrite = fopen(fWriteName,'wb');

% Read the data of correct data-type
dataType = 'int16';
% For more details on the Matlab supported data types: click here

numberOfSeconds = 300;
fSamp = 12.5e6;

tic
for ii = 1:1:numberOfSeconds

    numberOfwordsToReadPerTime = fSamp * 1 * 2;

   % Read from File
   dataFromFile = fread(fidRead,numberOfwordsToReadPerTime,dataType);

   % Write into the file
   fwrite(fidWrite,dataFromFile,dataType);

end

toc; % tic and toc gives the time taken by Matlab to complete the execution of the above for-loop.

% Close the files
fclose(fidRead);
fclose(fidWrite);

% 2a. Example for ASCII/text file containing numbers

a = magic(10); % generates 10x10 matrix of numbers
save bFile.txt a -ascii;

fid = fopen('bFile.txt','r');
d = fscanf(fid,'%f',20)  % just reads first 20 words into a column
fclose(fid);

%Skipping few number of words from the file requires exact number of bytes + %bytes for end-of-line.
% we can check the number of bytes read so far using the command 'ftell'


% 2b. Example for ASCII/text file containing numbers
%To read the 10x10 matrix
rowStart = 0;
rowColumn = 0;
rowEnd = 9;
colEnd = 9;

d2 = dlmread('bFile.txt','',[rowStart rowColumn rowEnd colEnd])



%Result


d =

    92
    99
     1
     8
    15
    67
    74
    51
    58
    40
    98
    80
     7
    14
    16
    73
    55
    57
    64
    41


d2 =

    92    99     1     8    15    67    74    51    58    40
    98    80     7    14    16    73    55    57    64    41
     4    81    88    20    22    54    56    63    70    47
    85    87    19    21     3    60    62    69    71    28
    86    93    25     2     9    61    68    75    52    34
    17    24    76    83    90    42    49    26    33    65
    23     5    82    89    91    48    30    32    39    66
    79     6    13    95    97    29    31    38    45    72
    10    12    94    96    78    35    37    44    46    53
    11    18   100    77    84    36    43    50    27    59

How to load the Matlab figure and extract data from the figure?

% To load figure

h = hgload('RectangularChipShape.fig')


get(h) % lists all the properties linked to this class

set(h) % lists all the properties that can be configured


Few examples:

set(gca,'fontsize',26);

hline = findobj(gcf, 'type', 'line');
hData = findobj(gcf, 'type', 'data');
set(hline,'LineWidth',4)
set(hline,'LineStyle',':')

idx = [4 5];
set(hline(idx),'Marker','*')


%To extract the data from the figure

axesObjs = get(h, 'Children'); %axes handles
dataObjs = get(axesObjs, 'Children'); %handles to low-level graphics objects in axes


objTypes = get(dataObjs{2});
xdata = get(dataObjs{2}, 'XData'); %data from low-level grahics objects
ydata = get(dataObjs{2}, 'YData');

%To extract data from Surf/Mesh plot
m = magic(10);

figure; h1 = mesh(m); % works for 'surf' also

h12 =gcf; % returns the figure number
 
h1Children = get(h12,'Children');
h1Chotas = get(h1Children,'Children'); % this is equal to h1
xD = get(h1Chotas,'xdata')
yD = get(h1Chotas,'ydata')
zD = get(h1Chotas,'zdata'


% Detailed explanation is available at:

http://www.mathworks.com/help/matlab/learn_matlab/understanding-handle-graphics-objects.html

Thursday, 5 December 2013

What are 'cells' in Matlab?

Cells = Arrays that can contain data of varying types and sizes.

More details at:

http://www.mathworks.com/help/matlab/cell-arrays.html

How to create 'structures' in Matlab?

Example: Following command creates a structure with various fields with different data types.

struct('ifData', zeros(1, 1000), 'fSamp', 10e6, 'fif',0.42e6, 'noOfBits',16,'complexOrReal','complex','prn',10)



>> struct('ifData', zeros(1, 1000), 'fSamp', 10e6, 'fif',0.42e6, 'noOfBits',16,'complexOrReal','complex','prn',10)

ans =
           ifData: [1x1000 double]
            fSamp: 10000000
              fif: 420000
         noOfBits: 16
    complexOrReal: 'complex'
              prn: 10


 

How to include folders into Matlab library search?

If we want to call some Matlab functions which are there in a separate folder (these files are not in the current working directory), then we can use 'addpath' command add that folder to library-search folders.

Example: If 'Acquisition' is a folder inside the working directory, then:

addpath Acqusition;

 %will add the folder and we can directly call the functions that are inside %'Acquisition' folder.

or, we can give the full absolute path of the folder:

addpath F:\Users\Naveen\UofC\638\Lab2\Work_code\Acqusition;


Sunday, 10 November 2013

How to save Matlab graphs/plots with high resolution/quality (suitable for publications)?

Use the export-figure file from:

http://www.mathworks.com/matlabcentral/fileexchange/23629-exportfig

Examples can be found at:

https://sites.google.com/site/oliverwoodford/software/export_fig


Other settings:

% Colour adjustmentsset(gcf, 'Color', 'w'); %background outside the plot
set(gca, 'Color', 'w'); %background of the plot

% Set figure format - Size
% set(gcf,'Position',[xpos ypos scale*width scale*height])
set(gcf, 'Position', [100 100 150 150])
%or,
scrsz = get(0,'ScreenSize'); %returns the screen size
set(gcf, 'Position', [0 0 0.85*scrsz(3) 1*scrsz(4)]);

% Saving figure using export_fig
figName = [fName(1:end-4) '.png'];

saveas(gcf, figName);
export_fig(figName);

% Example:

function [] = SaveAndExportFigure(figName)
set(gcf, 'Color', 'w'); %background outside the plot
set(gca, 'Color', 'w'); %background of the plot
scrsz = get(0,'ScreenSize');
set(gcf, 'Position', [0 0 0.85*scrsz(3) 1*scrsz(4)]);
saveas(gcf, figName);
export_fig(figName);
 









  
 
 
 
 
 

Wednesday, 23 October 2013

How to rotate (or align) the labels in 3D plots?

1. The 'rot' attribute gives the access to rotate the labels. We need to know the angle by which we need to rotate.

xlabel('xMagic','rot', 14,'fontweight','bold','fontsize',12); 
ylabel('yMagic','rot', -20,'fontweight','bold','fontsize',12);

How to plot the shadow in the 'surf' plot in Matlab?

1. Follow these hints: Thanks to the 'shadowplot' function from Mathworks.
z = magic(100);
surf(z);
shading interp;
shadowplot x;
shadowplot y;

xlabel('xMagic','rot', 14,'fontweight','bold','fontsize',12); 
ylabel('yMagic','rot', -20,'fontweight','bold','fontsize',12);
zlabel('zMagic','fontweight','bold','fontsize',14);

Example of Shadow plot:


2. The shadowplot x and shadowplot y demand 'x' and 'y' to be monotonically increasing. Due to Matlab's floating point representation problem (clearly explained HERE), we will not get monotonically increasing number even when we use: dx = 0: 0.01:1; This can be checked by:

dx = 0:0.01:1;
figure;
plot(diff(dx));

This will become a problem to use 'shadowplot'. One method that could be used is:

a. Plot the 3-D space
surf(corrValues); % instead of surf(x,y, corrValues);
shading interp;
shadowplot y;
shadowplot x;

%Now the plot x and y indices will be integers starting from 1 to size(corrValues) respectively. Off course, there will be (0,0) point but corrValues are not pointed at this point.


b. Now to have the x- and y-axis labelling as desired, instead of integers, following method could be used:

% Get the string from the number array
for ii = 1:2:length(xx)
   xTickLabel1(ii).a = num2str(xx(ii), 4);
end

xlbl = {xTickLabel1.a};

for ii = 1:1:length(yy)
 yTickLabel1(ii).a = num2str(yy(ii), 4);
end

ylbl = {yTickLabel1.a};

% Set the grid-lines -- x and y indices where grid lines to be shown
set(gca, 'XTick',[1:1:length(xx)]);
set(gca, 'YTick',[1:1:length(yy)]);
% Label the grid-lines that are selected above.
set(gca,'XTickLabel',xlbl)
set(gca,'YTickLabel',ylbl)

Tuesday, 22 October 2013

How to give names to each indices of an axis in Matlab?

Taken from Matlab help:

x = -pi:.1:pi;
y = sin(x);
p = plot(x,y)

set(gca,'XTick',-pi:pi/2:pi)

set(gca,'XTickLabel',{'-pi','-pi/2','0','pi/2','pi'})

xlabel('-\pi \leq \Theta \leq \pi')

ylabel('sin(\Theta)')

title('Plot of sin(\Theta)')

How to change the GRID size and Grid labels (of x, y, and z axis indices) in Matlab Plots?

1 . Simplest command is:

>> grid minor


2. If we need to customize the grid-line locations, then

a. Equal spacing:

set(gca,'xtick',[0:13:100])
set(gca,'ytick',linspace(-50,50,0))


b. Unequal spacing

xGrid = [-5 -2 -0 4 6 9]; %This need not cover the entire range of x. Where ever %grid-lines are needed we can have


set(gca,'ytick',[-50:2:0])

set(gca,'xtick',xGrid)

c. Example of playing with grid size and grid labels
%Code search space (x-axis) indices
xx = codeChipInd-1;
for ii = 1:2:length(xx)
  xTickLabel1(ii).a = num2str(xx(ii).*(fCode/fSamp), 4);
end
xlbl = {xTickLabel1.a};

%Frequency search space (y-axis) indices
yy = freqSearchRange(1:1:end);
for ii = 1:1:length(yy)
  yTickLabel1(ii).a = num2str(yy(ii), 4);
end
ylbl = {yTickLabel1.a};

% Set the grid-lines -- x and y indices where grid lines to be shown
%Define the grid-line locations
set(gca, 'XTick',[1:1200:length(xx)]); % selecting every 1200 samples (100 chips) (12.276 MHz Fs=> 12 samples per code)

set(gca, 'YTick',[1:10:length(yy)]); %selecting every 10 frequency bin

% Label the grid-lines that are selected above.
set(gca,'XTickLabel',xlbl(1:1200:end))
set(gca,'YTickLabel',ylbl(1:10:end))


GPS Acquisition: Delay and Frequency search space

Thursday, 3 October 2013

Linking axes of subplots while zooming in Matlab plots?


%To link the zooming of axes across subplots:
>> help linkaxes

How to control zooming in Matlab Plot?

% Just use the following commands:

%To zoom only on x-axis
zoom xon


%To zoom only on y-axis
zoom yon

%To control the zoom on individual subplots (this code is taken from Matlab help >> help zoom)
    ax1 = subplot(2,2,1);
    plot(1:10);
    h = zoom;
    ax2 = subplot(2,2,2);
    plot(rand(3));
    setAllowAxesZoom(h,ax2,false);
    ax3 = subplot(2,2,3);
    plot(peaks);
    setAxesZoomMotion(h,ax3,'horizontal');
    ax4 = subplot(2,2,4);
    contour(peaks);

    setAxesZoomMotion(h,ax4,'vertical');


How to Profile a Matlab program?

Simple ways

1. To measure the time taken by code, use 'tic and 'toc'.  'toc' gives the time elapsed from last 'tic' command.

1.5. To store the value of the time elapsed use:

timeSoFar = toc; %return the time elapsed from the last 'tic'

2. 'profile on' at the beginning of the program and at the end 'profile viewer' --- This gives detailed information about the time take by each functions.

For more info :

>>help tic

>>help profile

How to speed up Matlab execution?

Simple ways to speed up the Matlab program 

1. Use 'mlint' command to do the basic rule check -- This will give some hints.

2. If physical memory (RAM) is available, pre-allocate the memory for variables.
Ex :  If there is an array which grows in a for-loop to say 100x350. Then before the loop, initialize the array as, big_array = zeros(100,350);

3.  Use default Matlab function to the maximum possible extent. Those functions are written in C and they run much faster.

4.  Use array/vector operations instead of for-loops. It greatly reduces the time.
Example :
a) To generate a sine-wave of frequency fm sampled with fs for a duration of T.

clc;
clear;

fm = 1e6;
fs  = 10e6;
T = 1;

%Logic-1 (Faster)
tic;
t = 0 : (1/fs) : T-(1/fs);
s = sin(2*pi*fm*t);
toc

%Logic-2 (slow)
tic
for i = 1:1:(fs*T)
   s(i) = sin(2*pi*fm*i/fs);
end
toc

------Matlab output in 'seconds'----
logic1 =

    0.4162

logic2 =

    2.0926

b) Use 'find', 'reshape' commands to avoid loops. They are really useful.
>>help find

>> help reshape

5. Split the logic into sub-modules. And for every sub-modules write a function and use. This helps save the  memory (when the control returns from the function -- memory used by variables in those functions will be released automatically). This efficient memory usage in turn reduced the time of execution.

6.  Next is to use 'parfor' if there are loops where the iterations are independent of each other.
a. This requires, Parallel computing toolbox.
b. Easy way to use 'parfor' is by calling user written 'functions' which doesn't require input from previous index.
c. For this to work, type in
>> matlabpool open

Once Matlab detects the no.of.cores in the PC, it parallely executes the functions in the for-loop for every index.
d. Run you program with 'parfor'

7. In cases, where for-loops can't be avoided. Write those functions in C program and interface (MEX) those files with the Matlab. These functions are called in the same way as that of the normal Matlab functions. It is just that, they are pre-compiled using MEX. Then Matlab just runs this executable.

8. PLOT command is slow in expanding the array.
Example : t= 1:1:1000;
a = 10.23; %Slower for the floating point numbers
plot(t,a) ; % this takes more time than the one below.

a_arr = a * ones(1,length(t));
plot(t,a_arr);

9. Use 'single' precision than 'double' precision numbers --- It will double the speed
a. Matlab's default type is 'double' which takes 8 bytes of memory for every number that is created.
b. In case the program doesn't require the 64-bit precision, it can be changed to 'single' precision as given below:
t = 1:1:100; %(it is in double precision)
whos %this command lists all the variables in the workspace with their size & type information

y = single(t); %converting from double to single
whos % check the size of the y

10. Use array operations
a. Generating 40 complex sinusoids each with 20000 sample points
fIf = 1e6;
noOfFreqBins = 40;
freqSearchStepSize=100;
fSamp = 20e6;
codePeriod = 1e-3;
t  = single(0:1/fSamp:codePeriod-(1/fSamp));

carFreq1 = single((fIf - (noOfFreqBins/2-(1:1:noOfFreqBins))*freqSearchStepSize));
carFreq =  (repmat(carFreq1,length(t),1))'; %repeating the matrix
tt = repmat(t,length(carFreq1),1);
locSignal.carIq = single(exp(-1i*2*pi*carFreq(1:noOfFreqBins,:).*tt));

>> size(locSignal.carIq)
40  20000

b. If we had used for-loop it takes more time. Same idea can be used for all the other functions such as FFT, IFFT, etc. It runs really faster. However, this method requires more memory, as it has to store the entire array of many variables.

c. One thing to note here is that, this approach uses all the 'available CPU cores' even without using the 'matlabpool open' command.

This indicates that, Matlab might executes all the array operations in parallel.

In a particular program with both 'array operations' and 'parfor' command following observations were made, (in both the cases, 'single' precision is used)
  1. only 'array operations' and normal 'for' loop -- 20 seconds
  2. same 'array operations' with 'parfor' loop -- 40 seconds -- looks like here switching time to share the memory is more because of large arrays . This method performs better than normal 'for' loop when the 'arrays' are of less size.