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.






Interesting Matlab commands

1. Find and replace/extract a number or set of numbers in one command.
x = 1:1:20;
no_greater_than_5 = x( x>5 );
no_equal_to_5 = x( x==5 );
%It works for other conditional operations as well.

2. Find the INDICES of the SOME(based on a condition) numbers in an array.
x = 1:10:200;
ind_of_no_greater_than_5 = find(x>50)

3. Sum those numbers at the selected INDICES.
s = sum(  x ( ind_of_no_greater_than_5 ) )

%%Using these commands, for-loops can be avoided to increase the speed of execution.

4. Updating only the required elements in an array.
ind_to_be_updated = 1:2:100; % (alternate elements);
array(ind_to_be_updated) = array_with_50_numbers;

%This can be used to generated alternate ones and zeros. Like a clock. This is very useful for implementing the digital stuff in Matlab.

5. For storing the array of arrays with different no. of elements -- use structures.
array(1).a = ones(1,10);
array(2).a= ones(1,20);
array(3).a = ones(1,30);
array(4).b = zeros(30,1);

%To collate all the elements 'a' of the entire array use,
arr_total = [array.a]; %combines everything and gives
arr_total = {array.a}; % gives the individual 'a' s sizes








How to generate Square wave, of frequency fm, in Matlab?

How to generate Square wave, of frequency fm, in Matlab?
% let fm = 10Hz

fm = 10;
fs = 1000; %Hz -- sampling frequency
t = 0:(1/fs):1;
squareWave = sign(sin(2*pi*fm*t));

How to generate 3D plots in Matlab ?

How to generate 3D plots in Matlab ?

Use 'surf' command in Matlab

Example:

figure;
x = 1:100;
y = 1:100;
z = magic(100);
surf(x,y,z);

Another example to plot the correlation values of the GPS signal:

figure;
% fSamp = sampling frequency
% fCode = 1.023e6;
% fIf = Intermediate frequency, carFreqs -- dopplers
% x - chip axis
% y - frequency axis
% z - correlation values

x = (1:1:fSamp*1e-3)*fCode./fSamp;
y = carFreqs - fIf;
surf(x,y,abs(corrVal));

How to reorganize the contents of an array/matrix in Matlab?

How to reorganize the contents of an array/matrix in Matlab?

Use 'reshape' command in Matlab.

>> help reshape


Example:

>> ss = magic(4)

ss =

    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

>> d = reshape(ss,8,2)

d1 =

    16     3
     5    10
     9     6
     4    15
     2    13
    11     8
     7    12
    14     1

>> d2 = reshape(ss,2,8)

d2 =

    16     9     2     7     3     6    13    12
     5     4    11    14    10    15     8     1

Note: reshape works 'COLUMN' wise.