; MATLAB | Michael Ian Lapsley
Showing posts with label MATLAB. Show all posts
Showing posts with label MATLAB. Show all posts

Installing, modifying and using Octave in Windows

Install octave


  • http://wiki.octave.org/Octave_for_Windows
  • Follow all of the instructions for 3.6.4 explicitly!
  • It is recommended to install the files here: C:\Octave

Add the folder containing the octave excitable to the path


  • Location of octave on my computer: C:\Octave\Octave3.6.4_gcc4.6.2\bin
  • Adding to path
  • Right click on my computer
  • Properties
  • Advanced tab
  • Environment Variables button
  • System variables
  • Click on path variable
  • Click edit button
  • DO NOT DELETE ANY INFORMATION IN THE CURRENT PATH
  • Add “;C:\Octave\Octave3.6.4_gcc4.6.2\bin” at the end of the path
  • Save

Test octave


  • Open cmd window
  • Type “octave”
  • Octave should run in the cmd window

Basics for .bat file


  • Comments
    • “rem” is the command used to create comments in a .bat file
    • rem this is a comment
  • Goto
    • Set a location
      • :Location1
    • Go to it
      • @goto Location1
  • Display text
    • @echo “text to display”
  • Turn off displaying automatic text
    • @ echo off
  • Variables
    • SET /P unit="Please Enter Unit: "
    • %unit%

Running octive files from .bat


  • Open a new file in a text editor and save it as a .bat file
  • http://www.gnu.org/software/octave/doc/interpreter/Invoking-Octave-from-the-Command-Line.html
  • http://www.gnu.org/software/octave/doc/interpreter/Startup-Files.html
  • Setting path in .bat does not work
  • octave --exec-path --eval helloworld.m
  • Set (or determine) the default octave directory File located here:
    • octave-home/share/octave/site/m/startup/octaverc
    • Put the file to be run in the default location
  • Evaluate the file to be run in the .bat file
    • octave --eval helloworld.m
    • an error appears but it seems to be of no consequence
    • error: can't perform indexing operations for <unknown type> type


[Matlab] Figure and axis options

In Matlab, if you type get(gcf) of get(gca) you will get a list of the current properties of the given axis or figure. Also, set(gcf) or set(gca) will list all available properties and the legal options you can set. This is true for other objects also. I tend to use figures and axes regularly and forget these option and so I am listing them here.

set(gcf):  
 
Alphamap
    CloseRequestFcn: string -or- function handle -or- cell array
    Color
    Colormap
    CurrentAxes
    CurrentCharacter
    CurrentObject
    CurrentPoint
    DockControls: [ {on} | off ]
    FileName
    IntegerHandle: [ {on} | off ]
    InvertHardcopy: [ {on} | off ]
    KeyPressFcn: string -or- function handle -or- cell array
    KeyReleaseFcn: string -or- function handle -or- cell array
    MenuBar: [ none | {figure} ]
    Name
    NextPlot: [ new | {add} | replace | replacechildren ]
    NumberTitle: [ {on} | off ]
    PaperUnits: [ {inches} | centimeters | normalized | points ]
    PaperOrientation: [ {portrait} | landscape | rotated ]
    PaperPosition
    PaperPositionMode: [ auto | {manual} ]
    PaperSize
    PaperType: [ {usletter} | uslegal | A0 | A1 | A2 | A3 | A4 | A5 | B0 | B1 | B2 | B3 | B4 | B5 | arch-A | arch-B | arch-C | arch-D | arch-E | A | B | C | D | E | tabloid | <custom> ]
    Pointer: [ crosshair | fullcrosshair | {arrow} | ibeam | watch | topl | topr | botl | botr | left | top | right | bottom | circle | cross | fleur | custom | hand ]
    PointerShapeCData
    PointerShapeHotSpot
    Position
    Renderer: [ {painters} | zbuffer | OpenGL | None ]
    RendererMode: [ {auto} | manual ]
    Resize: [ {on} | off ]
    ResizeFcn: string -or- function handle -or- cell array
    SelectionType: [ normal | open | alt | extend ]
    ToolBar: [ none | {auto} | figure ]
    Units: [ inches | centimeters | normalized | points | {pixels} | characters ]
    WindowButtonDownFcn: string -or- function handle -or- cell array
    WindowButtonMotionFcn: string -or- function handle -or- cell array
    WindowButtonUpFcn: string -or- function handle -or- cell array
    WindowKeyPressFcn: string -or- function handle -or- cell array
    WindowKeyReleaseFcn: string -or- function handle -or- cell array
    WindowScrollWheelFcn: string -or- function handle -or- cell array
    WindowStyle: [ {normal} | modal | docked ]
    WVisual: { 00 (RGB 32  GDI, Bitmap, Window) }
  01 (RGB 32 bits(08 08 08 08) zdepth  0, Hardware Accelerated, Opengl, Window)
  02 (RGB 32 bits(08 08 08 08) zdepth  0, Hardware Accelerated, Opengl, Double Buffered, Window)
  03 (RGB 32 bits(08 08 08 08) zdepth 16, Hardware Accelerated, Opengl, Window)
  04 (RGB 32 bits(08 08 08 08) zdepth 16, Hardware Accelerated, Opengl, Double Buffered, Window)
  05 (RGB 32 bits(08 08 08 08) zdepth 24, Hardware Accelerated, Opengl, Window)
  06 (RGB 32 bits(08 08 08 08) zdepth 24, Hardware Accelerated, Opengl, Double Buffered, Window)
  07 (RGB 32 bits(08 08 08 00) zdepth 32, Generic, Opengl, GDI, Bitmap, Window)
  08 (RGB 32 bits(08 08 08 00) zdepth 16, Generic, Opengl, GDI, Bitmap, Window)
  09 (RGB 32 bits(08 08 08 00) zdepth 32, Generic, Opengl, Double Buffered, Window)
  10 (RGB 32 bits(08 08 08 00) zdepth 16, Generic, Opengl, Double Buffered, Window)
  11 (RGB 32 bits(08 08 08 08) zdepth 32, Generic, Opengl, GDI, Bitmap, Window)
  12 (RGB 32 bits(08 08 08 08) zdepth 16, Generic, Opengl, GDI, Bitmap, Window)
  13 (RGB 32 bits(08 08 08 08) zdepth 32, Generic, Opengl, Double Buffered, Window)
  14 (RGB 32 bits(08 08 08 08) zdepth 16, Generic, Opengl, Double Buffered, Window)

    WVisualMode: [ {auto} | manual ]

    ButtonDownFcn: string -or- function handle -or- cell array
    Children
    Clipping: [ {on} | off ]
    CreateFcn: string -or- function handle -or- cell array
    DeleteFcn: string -or- function handle -or- cell array
    BusyAction: [ {queue} | cancel ]
    HandleVisibility: [ {on} | callback | off ]
    HitTest: [ {on} | off ]
    Interruptible: [ {on} | off ]
    Parent
    Selected: [ on | off ]
    SelectionHighlight: [ {on} | off ]
    Tag
    UIContextMenu
    UserData
    Visible: [ {on} | off ]

--------------------------------------------------------------------------------------------------------

set(gca):

    ActivePositionProperty: [ position | {outerposition} ]
    ALim
    ALimMode: [ {auto} | manual ]
    AmbientLightColor
    Box: [ on | {off} ]
    CameraPosition
    CameraPositionMode: [ {auto} | manual ]
    CameraTarget
    CameraTargetMode: [ {auto} | manual ]
    CameraUpVector
    CameraUpVectorMode: [ {auto} | manual ]
    CameraViewAngle
    CameraViewAngleMode: [ {auto} | manual ]
    CLim
    CLimMode: [ {auto} | manual ]
    Color
    ColorOrder
    DataAspectRatio
    DataAspectRatioMode: [ {auto} | manual ]
    DrawMode: [ {normal} | fast ]
    FontAngle: [ {normal} | italic | oblique ]
    FontName
    FontSize
    FontUnits: [ inches | centimeters | normalized | {points} | pixels ]
    FontWeight: [ light | {normal} | demi | bold ]
    GridLineStyle: [ - | -- | {:} | -. | none ]
    Layer: [ top | {bottom} ]
    LineStyleOrder
    LineWidth
    MinorGridLineStyle: [ - | -- | {:} | -. | none ]
    NextPlot: [ new | add | {replace} | replacechildren ]
    OuterPosition
    PlotBoxAspectRatio
    PlotBoxAspectRatioMode: [ {auto} | manual ]
    Projection: [ {orthographic} | perspective ]
    Position
    TickLength
    TickDir: [ {in} | out ]
    TickDirMode: [ {auto} | manual ]
    Title
    Units: [ inches | centimeters | {normalized} | points | pixels | characters ]
    View
    XColor
    XDir: [ {normal} | reverse ]
    XGrid: [ on | {off} ]
    XLabel
    XAxisLocation: [ top | {bottom} ]
    XLim
    XLimMode: [ {auto} | manual ]
    XMinorGrid: [ on | {off} ]
    XMinorTick: [ on | {off} ]
    XScale: [ {linear} | log ]
    XTick
    XTickLabel
    XTickLabelMode: [ {auto} | manual ]
    XTickMode: [ {auto} | manual ]
    YColor
    YDir: [ {normal} | reverse ]
    YGrid: [ on | {off} ]
    YLabel
    YAxisLocation: [ {left} | right ]
    YLim
    YLimMode: [ {auto} | manual ]
    YMinorGrid: [ on | {off} ]
    YMinorTick: [ on | {off} ]
    YScale: [ {linear} | log ]
    YTick
    YTickLabel
    YTickLabelMode: [ {auto} | manual ]
    YTickMode: [ {auto} | manual ]
    ZColor
    ZDir: [ {normal} | reverse ]
    ZGrid: [ on | {off} ]
    ZLabel
    ZLim
    ZLimMode: [ {auto} | manual ]
    ZMinorGrid: [ on | {off} ]
    ZMinorTick: [ on | {off} ]
    ZScale: [ {linear} | log ]
    ZTick
    ZTickLabel
    ZTickLabelMode: [ {auto} | manual ]
    ZTickMode: [ {auto} | manual ]

    ButtonDownFcn: string -or- function handle -or- cell array
    Children
    Clipping: [ {on} | off ]
    CreateFcn: string -or- function handle -or- cell array
    DeleteFcn: string -or- function handle -or- cell array
    BusyAction: [ {queue} | cancel ]
    HandleVisibility: [ {on} | callback | off ]
    HitTest: [ {on} | off ]
    Interruptible: [ {on} | off ]
    Parent
    Selected: [ on | off ]
    SelectionHighlight: [ {on} | off ]
    Tag
    UIContextMenu
    UserData
    Visible: [ {on} | off ]

[Matlab] Colors and Symbols for ploting in loops

Sometimes it is easier to use a loop to plot something rather than manually typing plot many times. The problem is that all of the lines will have the same color and all the symbols will be the same. This code easily applies color to plots in a loop.


[Matlab] User Interface Functions

One easy method for creating a user interface is a question dialog. This can easily be used with the switch function to run different sections of code.

SelectFunction = questdlg('What do you want to do?', ...
                'Select Function', ...
                'Get data from images', 'Get Amplitude information from data','Plot displacement vs. time','Get data from images');
switch SelectFunction
   
%% Input data from images
    case 'Get data from images'

      'Stuff'
    
    case 'Get Amplitude information from data'
      'more stuff'

A more complex but useful process is this:

function UserInterfaceExample

% User Interface Example
% Creates a box with buttons which execute functions
 
    clear;clc;close all;
    height = 250;
    width = 200;
    figure
    set(gcf,'Position',[1000 height+200 width height],'Menubar','none')
   
    uicontrol('Style', 'pushbutton', 'String', 'Say Hi',...
            'Position', [50 height-50 100 20],...
            'Callback', @Function1);
   
    uicontrol('Style', 'pushbutton', 'String', 'Say Bye',...
        'Position', [50 height-100 100 20],...
        'Callback', @Function2);
   
    uicontrol('Style', 'pushbutton', 'String', 'Draw a Line',...
        'Position', [50 height-150 100 20],...
        'Callback', @Function3);
   
    uicontrol('Style', 'pushbutton', 'String', 'Draw Shapes',...
        'Position', [50 height-200 100 20],...
        'Callback', @Function4);
end

function Function1(src,evt)
    clear;clc;close all;
    fprintf('HI')

end

function Function2(src,evt) 
    clear;clc;close all;
    fprintf('Bye!') 
end
    
function Function3(src,evt)

    clear;clc;close all; 
    figure
    line([2 5],[2 5])
end

function Function4(src,evt)
    clear; clc; close all;
    figure
    rectangle('Position',[200 200 300 500],'Curvature', [0 0])
    rectangle('Position',[10 10 300 500],'curvature',[1,1])
    axis square

end


other functions:

uicontrol
uigetdir
uigetfile
inputdlg
errordlg
helpdlg
listdlg
msgbox
questdlg
uiresume
uiwait
warndlg
end

[Matlab] Adding ASCII Charecters for abvanced ploting

Some times in Matlab one may want to add some charecter in the code. Here is an example:

Lets say you want to plot several variables with similar names (like A1, A2, A3) using a for loop as such:

A1 = 0:5;
A2 = 5:10;
A3 = 10:15;
for i = 1:3
    eval(['plot(A',num2str(i),')'])
    hold on
end

This will work but all of your plots will have the same line type, symbol color etc. Now it you want to add different colors to a plot you can use strings to define the colors. But using the eval function creates problems because you must create a string within a string. usually you can use this notation:

String = 'Here is another "string" in this string'

However with the eval function this does not work for me. However, ASCII charecters can be created using the char command. So to add colors to the plot:


A1 = 0:5;
A2 = 5:10;
A3 = 10:15;

colors = [1 0 0; 0 1 0; 0 0 1];
for i = 1:3
    eval(['plot(A',num2str(i),',',char(039),'color',char(039),',colors(i,:))'])
    hold on
end

A list of ASCII character codes are found here:
http://www.asciitable.com/

use the char() command to insert the charecters

Here is a good list of colors and symbols to use with these plots:

symbol = {'o','s','^','v','<','>','d','p'};
colors = [  0   0   0
            0.8 0   0
            1   0   0
            1   0.6 0
            0   0.6 0
            0   0   1
            0   0   0.6
            0.8 0   0.8
                        ];

[Matlab] Training from Steven

here is the link - http://goo.gl/Lu7Qg

[Matlab] Loading Large Data Sets

The Old Way to Load DataSets

Lots of my time consists of analyzing huge sets of files recorded by and oscilloscope or some other device. Typically, I would try to use the same name for each file with a number at the end that increase each time. Then I can write a loop to load all of the files, then do analysis and create plots. This causes its own problems for several reasons such as: several loops must be used for different regions of the data (tek0000n for n = 1-9; tek000nn for nn = 10-99; tek00nnn for nnn = 100-999; etc) and broken loops when a single file in the data set is a different length or mission, and many other issues. Such a sustem looks like this where many conditional loops are used to fix the problem:

if m <10 & n < 10
   for i = 1:n
       Temp = dlmread([File,'/',File,'-0000',num2str(i),'.txt'],'\t',[17 0 3664 1]);
       Frequency(:,i) = Temp(:,1);
       Absorption(:,i) = Temp(:,2);
   end
end

if m <10 & n < 100 & n > 10
   for i = 1:9
       Temp = dlmread([File,'/',File,'-0000',num2str(i),'.txt'],'\t',[17 0 3664 1]);
       Frequency(:,i) = Temp(:,1);
       Absorption(:,i) = Temp(:,2);
   end
           
   for i = 10:n
       Temp = dlmread([File,'/',File,'-000',num2str(i),'.txt'],'\t',[17 0 3664 1]);
       Frequency(:,i) = Temp(:,1);
       Absorption(:,i) = Temp(:,2);
   end
end
       
if m <10 & n < 1000 & n > 100
   for i = 1:9
       Temp = dlmread([File,'/',File,'-0000',num2str(i),'.txt'],'\t',[17 0 3664 1]);
       Frequency(:,i) = Temp(:,1);
       Absorption(:,i) = Temp(:,2);
   end
           
   for i = 10:99
       Temp = dlmread([File,'/',File,'-000',num2str(i),'.txt'],'\t',[17 0 3664 1]);
       Frequency(:,i) = Temp(:,1);
       Absorption(:,i) = Temp(:,2);
   end
           
   for i = 100:n
       Temp = dlmread([File,'/',File,'-00',num2str(i),'.txt'],'\t',[17 0 3664 1]);
       Frequency(:,i) = Temp(:,1);
       Absorption(:,i) = Temp(:,2);
   end
end
       
if m > 10 & n < 1000 & n > 100
   for i = m:99
       Temp = dlmread([File,'/',File,'-000',num2str(i),'.txt'],'\t',[17 0 3664 1]);
       Frequency(:,i) = Temp(:,1);
       Absorption(:,i) = Temp(:,2);
   end
           
   for i = 100:n
        Temp = dlmread([File,'/',File,'-00',num2str(i),'.txt'],'\t',[17 0 3664 1]);
        Frequency(:,i) = Temp(:,1);
        Absorption(:,i) = Temp(:,2);
   end
end
       
if m < 10 & n > 1000
   for i = 1:9
       Temp = dlmread([File,'/',File,'-0000',num2str(i),'.txt'],'\t',[17 0 3664 1]);
       Frequency(:,i) = Temp(:,1);
       Absorption(:,i) = Temp(:,2);
   end
          
   for i = 10:99
       Temp = dlmread([File,'/',File,'-000',num2str(i),'.txt'],'\t',[17 0 3664 1]);
       Frequency(:,i) = Temp(:,1);
       Absorption(:,i) = Temp(:,2);
   end
           
   for i = 100:999
       Temp = dlmread([File,'/',File,'-00',num2str(i),'.txt'],'\t',[17 0 3664 1]);
       Frequency(:,i) = Temp(:,1);
       Absorption(:,i) = Temp(:,2);
   end  
end

Read Directory and Load

Recently, google helped me discover a better method where you can actually tell matlab to read and record the files names in a specific folder. The, so long as all the data is the same length, a single loop can be used to import all of the data in a single folder. Here is an example:

clear;clc;close all

cd ..
Temp = dir('Data');
Temp2 = {Temp.name};
FileName = Temp2(3:end);

for i = 1:length(FileName)
    Temp = dlmread(['Data/',char(FileName(i))],',',[14 0 10013 2]);
    time = Temp(:,1);
    ch1 = Temp(:,2);
    ch2 = Temp(:,3);
    save(['[Matlab]/MData/DataSet',num2str(i),'.mat'],'time','ch1','ch2')
end

return


The dir command reads the folder \Data, and a structure cell is created with the information for each file. Since I only care about the name, that cell can be extracted and trimmed. Then a single loop can be used to load all of the data into a useful format. To prevent errors if the files are not the same length, each data set is save in its own .mat file. These files can be quickly loaded in Matlab for later use.

Loading several .mat files

Once all of the data is stored in separate .mat files, this data can be easily accessed and plotted. It one were to plot the first 5 data sets that were loaded above, this code would perform the operation:


for i = [1:5]
    Str = ['MData\DataSet',num2str(i),'.mat'];
    load(Str)
    eval(['time_',num2str(i),' = time;'])
    eval(['ch1_',num2str(i),' = ch1;'])
    eval(['ch2_',num2str(i),' = ch2;'])
end

figure
hold on
        
for i = 1:5
    eval(['plot(time_',num2str(i),',ch1_',num2str(i),')'])
end

hold off

I realize that there are many non standard matlab functions here, but I encourage people to learn these functions. They have been very useful for me in performing some more advanced actions.



Refractive Index of Water

Due to the effects of optical dispersion, the refractive index of water is dependent on the wavelength of light being used. After a long search, I found a good reference for this information (Daimon and Masumura). here is a plot of their data in the visible range:


Matlab was used to fit a exponential decay function to the 20oC data:

y = a e-bx  + c
where:
a = 0.1140
b = 0.0048
c = 1.3264

Here is a plot of the fit with the data:

****NOTE** This fit is only valid from 400 nm to 800 nm and is not perfect ****
Here is a Calculator to solve this fit:

Equation Solver

This program solves ae-bx + c using java script imbedded in HTML. This is intended to solve the exponential function to determine the refractive index of water at different wavelengths.
Here are the inputs:
a:
b:  
c:  
x:  
(wavelength of light in nanometers)
Solution to ae-bx + c:
Output: