Tuesday 8 December 2009

Simple way to pass numeric array from c# to matlab.

This is a follow up screencast on Matlab Neural Network in C# Application (http://baijumax.blogspot.com/2009/05/matlab-neural-network-in-c-application.html),users often face issues with passing array from c# to matlab and based on their feedback I have decided to prepare this
screen cast in which I have shown simple solution to get around with syntactical issues of passing numeric array from c# to matlab by using simple string array.

Sunday 1 November 2009

Creating simple WPF Multi-Thread application.

This videos shows how to create simple wpf -thread application,gives an overview of how to use "Dispatcher" object in WPF.




Below extension method will allow us to update any controls in thread safe manner.

public static class ControlExtension
{
public static void UpdateControlSafe(this Control control, Action code)
{
if (!control.Dispatcher.CheckAccess())
control.Dispatcher.BeginInvoke(code);
else
code.Invoke();
}
}

Monday 29 June 2009

Generic InvokeRequired pattern - (C# Multi-Threading)

Tody I read article on InokeRequired patterns posted in code project ( Read Full Article )

I have wrote more generic version of the same ( Less code !!!!! ...clear & crisp...)

public static class ControlExtension
{
public static void UpdateControl(this Control control, MethodInvoker code)
{
if (control.InvokeRequired) {
control.Invoke(code);
}
else{
code.Invoke();
}
}

using 'Control' type param in Extension mentod give us an advantage to call UpdateControl on any control.

for eg:- In the below example I have called 'UpdateControl' extension method on textbox control.

private void btnUpdate_Click(object sender, EventArgs e)
{
Thread th = new Thread(new ThreadStart( () => txtInfo.UpdateControl(Display) ) );
th.Start();
}

private void Display()
{
txtInfo.Text += "Updated";
}

Saturday 13 June 2009

Using Web Services with MATLAB

This video explains how to consume Web services in matlab.

Note:- use 'createClassFromWsdl' function to generate matlab equivalent proxy class from wsdl.




Code snippet of Currency converter GUI application that is used for this demo,

file name :- CurrencyConverterGUI.m
------------------------------------

function varargout = CurrencyConverterGUI(varargin)
% CURRENCYCONVERTERGUI M-file for CurrencyConverterGUI.fig
% CURRENCYCONVERTERGUI, by itself, creates a new CURRENCYCONVERTERGUI or raises the existing
% singleton*.
%
% H = CURRENCYCONVERTERGUI returns the handle to a new CURRENCYCONVERTERGUI or the handle to
% the existing singleton*.
%
% CURRENCYCONVERTERGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in CURRENCYCONVERTERGUI.M with the given input arguments.
%
% CURRENCYCONVERTERGUI('Property','Value',...) creates a new CURRENCYCONVERTERGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before CurrencyConverterGUI_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to CurrencyConverterGUI_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help CurrencyConverterGUI

% Last Modified by GUIDE v2.5 13-Jun-2009 08:58:28

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @CurrencyConverterGUI_OpeningFcn, ...
'gui_OutputFcn', @CurrencyConverterGUI_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before CurrencyConverterGUI is made visible.
function CurrencyConverterGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to CurrencyConverterGUI (see VARARGIN)

% Choose default command line output for CurrencyConverterGUI
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes CurrencyConverterGUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = CurrencyConverterGUI_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu1


% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in ToCurrency.
function ToCurrency_Callback(hObject, eventdata, handles)
% hObject handle to ToCurrency (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns ToCurrency contents as cell array
% contents{get(hObject,'Value')} returns selected item from ToCurrency


% --- Executes during object creation, after setting all properties.
function ToCurrency_CreateFcn(hObject, eventdata, handles)
% hObject handle to ToCurrency (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in FromCurrency.
function FromCurrency_Callback(hObject, eventdata, handles)
% hObject handle to FromCurrency (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns FromCurrency contents as cell array
% contents{get(hObject,'Value')} returns selected item from FromCurrency


% --- Executes during object creation, after setting all properties.
function FromCurrency_CreateFcn(hObject, eventdata, handles)
% hObject handle to FromCurrency (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end



function convertedValue_Callback(hObject, eventdata, handles)
% hObject handle to convertedValue (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of convertedValue as text
% str2double(get(hObject,'String')) returns contents of convertedValue as a double


% --- Executes during object creation, after setting all properties.
function convertedValue_CreateFcn(hObject, eventdata, handles)
% hObject handle to convertedValue (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in Convert.
function Convert_Callback(hObject, eventdata, handles)
% hObject handle to Convert (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

%instantiate object
service = CurrencyConvertor;

fromCurrency = getSelectedValueFromPopupMenu(handles.FromCurrency);
toCurrency = getSelectedValueFromPopupMenu(handles.ToCurrency);

value = ConversionRate(service, fromCurrency,toCurrency);
set(handles.convertedValue,'String',value);

function [selectedValue] = getSelectedValueFromPopupMenu(handle)
contents = get(handle,'String');
selectedValue = contents{ get(handle,'value') };

Friday 29 May 2009

Creating GUI applications with Matlab.

Quick start to matlab gui programming using 'guide'.




Note:- It is easy to convert matlab GUI applications to windows standalone executable and run the converted executable (.exe file) in any machine in which matlab is not installed.For details check 'deploytool' matlab documentation.

Monday 18 May 2009

F# - New language for scientific computing From Microsoft.

Last Saturday I have got opportunity (or time :-)) to watch a screencast by Luca Bolognese on Functional language F# from MS.Watch the videohere.

My first impression on F# is that difficult syntax as compared to matlab but I believe there will be lot more language enhancements in coming release. Huge promise for Quant. Finance applications as we can easily integrate F# libs with other dotnet languages.

You can download F# September 2008 CTP from here

I will try to update my blog with some Quant. Libs written in F#.

Monday 4 May 2009

Matlab Neural Network in C# Application

Part 1 gives an overview of Matlab Network manager . This screen cast shows how to create XOR network using Matlab Network Manager.




This part explains how to use Matlab Neural Network in c# windows application and limitation of Matlab complier with respect to 'sim' function.

Note:- Don't forget to watch next episode of this series, in which I have explained how to get around with 'sim' function compiler limitation and call Neural network from c# windows application




In this part I have explained how to get around with 'sim' function compiler limitation and call Neural network from c# windows application.

Thursday 9 April 2009

Multi-Threading (.Net) :- System.Timer.Time class

Dotnet provides a server-based timer ( and is different from System.Windows.Forms.Timer and System.Threading.Timer ), allow us to specify a recurring interval at which an event will be raised in our application(or Easy way of executing a task at specified interval).


Below example (c# console application) shows how to create a Timer ,execute a task at specified interval and how to stop Timer gracefully.

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Timers;

namespace BackgroundThread_Terminate
{

class Program
{
static void Main(string[] args)
{
using (TimerClass_example1 timerSample = new TimerClass_example1())
{

Console.ReadLine();
}

Console.ReadLine();
}
}


public class TimerClass_example1:IDisposable
{
System.Timers.Timer timer;

long _stopTimer = 0; // 0 for start , 1 for stop

ManualResetEvent manualReset = new ManualResetEvent(false);

public TimerClass_example1()
{
timer = new System.Timers.Timer(1000);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}

//call back function excuted on a threadpool thread.
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
//always use try catch in callback
try
{
//gracefully stop timer
if(Interlocked.Read(ref _stopTimer) == 1 )
{
timer.Stop();
//signal the thread which is waiting.
manualReset.Set();

return;
}

Console.WriteLine(string.Format("Executed callback at {0}. Threadpool Thread ID:- {1}", DateTime.Now.ToString(), Thread.CurrentThread.ManagedThreadId));

//Note #1:- Uncomment below the and note the ThreadID's printed
//Thread.Sleep(2000); //[ Reason for printing different Thread is :- The Elapsed event is raised on a ThreadPool thread. If processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. Thus, the event handler should be reentrant.]
}
catch (Exception ex)
{
//log exception and you can stop excuting Timer.
}
}


public void Dispose()
{
StopAndDisposeTimer();
GC.SuppressFinalize(this);

Console.WriteLine("Timer has been disposed");
}

private void StopAndDisposeTimer()
{
Interlocked.Exchange(ref _stopTimer, 1);

//wait 5 secs for signal
if (!manualReset.WaitOne(5000, false))
{
Console.WriteLine("Timer is not stopped gracefully.");
}

timer.Dispose();
}

~TimerClass_example1()
{
Dispose();
}
}
}

Monday 2 March 2009

Developing Financial Applications using .Net & Matlab ( Part-1)

This video shows how we can use Algorithms written in matlab 'M' code can be used in .Net applications. (View the video in 'double size' resolution).



Matlab Code snippet
--------------------

function [ Price,AccruedInt ] = MyBndPrice(Yield, CouponRate, Settle,...
Maturity, Period, Basis)

[Price, AccruedInt] = bndprice(Yield, CouponRate, Settle,...
Maturity, Period, Basis);
end



.Net Code snippet
-------------------
private void btnBndPrice_Click(object sender, EventArgs e)
{

MWNumericArray yields = GetYields();
MWNumericArray coupon = new MWNumericArray(Convert.ToDouble(txtCoupon.Text) ) ;
MWNumericArray period = new MWNumericArray(cmbPeriod.SelectedIndex + 1 ) ;
MWNumericArray basis = new MWNumericArray(cmbBasis.SelectedIndex);

MWCharArray settlement = new MWCharArray(txtSettlement.Text);
MWCharArray maturity = new MWCharArray(txtMaturity.Text);

MyFinLib.MyFinLibclass finLib = new MyFinLib.MyFinLibclass();
MWArray[] result = finLib.MyBndPrice(2, yields, coupon, settlement, maturity, period, basis);

Display(result);

}

private double[] GetYields()
{
string[] yieldStr = txtYield.Text.Split(',');

double[] yields = new double[ yieldStr.Length ];
for (int i = 0; i < yieldStr.Length; i++)
yields[i] = Convert.ToDouble(yieldStr[i]);

return yields ;
}

private void Display(MWArray[] result)
{

DataTable dt = new DataTable();
dt.Columns.Add("Price");
dt.Columns.Add("Accrued Interest");

string[] price = result[0].ToString().Split('\n');
string[] accuredInt = result[1].ToString().Split('\n');


for (int i = 0; i < price.Length; i++)
{
DataRow row = dt.NewRow();
row[0] = price[i];
row[1] = accuredInt[i];

dt.Rows.Add(row);
}

dataGridView1.DataSource = dt;
}

Tuesday 10 February 2009

Visual Representation of SQL Joins + Set Notations

Throwing some Gyan on Sql Join/Set theory after reading an article on
Sql Joins in codeproject.

[Thanks to good old shool days set theory lectures.]

'A' & 'B' are two sets,

1) A n B = Inner Join ( 'n' -- Intersection)

2) A u (A n B) = left join ( 'u' -- union )

3) (A n B) u B = right join

4) A u B u (A n B) = outer join

5) A - B = Left join excluding inner join or relative complement

6) B - A = right join excluding inner join

7) (A - B) U (B - A) = outer join excluding inner join.

[Note:- Given the fact that Sql Joins are popular tech. interview question,you can use above stuff to impress your interviewer.I hope above set notions will help you to answer Sql Join Q?'s in a generic way rather than explaining using 'Table1' , 'Table2' etc.... ]

Thursday 22 January 2009

Vedic Math Part-1

What is a Number? Why students afraid to play with numbers?

These questions lead me to explore more on Vedic mathematics and found some interesting tips & tricks that will help to do your math calculation easily , without the help of Calculator.

“Vedic Mathematics is the name given to the ancient system of Mathematics which was rediscovered from the Vedas between 1911 and 1918 by Sri Bharati Krsna Tirthaji (1884-1960). According to his research all of mathematics is based on sixteen sutras, or word-formulae. For example, 'Vertically and Crosswise` is one of these Sutras. These formulae describe the way the mind naturally works and are therefore a great help in directing the student to the appropriate method of solution”.

Sharing some tips/tricks that I have learned, (start practising or teach your kids :-))


How to find the square of a number?

Ans: - #1) Generic way

[ Eg:- 8 x 8 = ?

Take 10 as base ,

step i) then find how much less/surplus is 8 from 10

i.e 8 -10 = -2 ( 8 is less than 10 so -2)

step ii) add less/surplus from the actual number, this will be right hand side digit

i.e (8-2) = 6

step iii) take the sqaure of surplus/less , this will be left hand digit

(-2) x (-2) = 4

So the answers is 64.

Similarly , 7 x 7 = ( 7 + ( 7 - 10)) ( (7-10) x (7-10) ) = ( 7 - 3) (-3 x -3) = 4 9

12 x 12 = ( 12 + (12 - 10) ) ( (12 - 10) x (12 - 10) ) = (12 + 2) (2 x 2) = 14 4 ( Note:- 12 is greater than 10 , so +2 )

try 13 x 13 = ?

]

#2) Square of number that ends with 5

15 x 15 = ?

Take the suqare of lefthand digit , ie 5 x 5 =25

add + 1 to right hand digit/digits and multiply that number with actual number ie 1 x (1 + 1 ) = 2

Answers is 2 25 , i.e. (1 x (1 + 1 )) ( 5 x 5 )

25 x 25 = ( 2 x ( 2 + 1) ) (5 x 5) = ( 2 x 3 ) 25 = 6 25

more to follow…….

Thursday 8 January 2009

Satyam/Asatyam SAGA

Satyam Shivam Sundaram (meaning, "Truth is God and God is beautiful") , but not in the case of India's fourth largest IT company
(http://profit.ndtv.com/2009/01/07113013/Satyam-chairman-Ramalinga-Raju.html).

I hope SEBI will act quickly & will save the image of Indian IT industry.

Sunday 4 January 2009

Screencast- Sorting the contents of CSV file

This screencast shows how to sort the contents of CSV file using Microsoft Text Driver and ADODB. (Note:- you can watch the same screencast here http://video.google.com/googleplayer.swf?docid=2082004182954594811&hl=en&fs=true in a better resolution)



Code Snippet
-------------
private void button1_Click(object sender, EventArgs e)
{
Connection connection = null;
try
{
connection = new ConnectionClass();

string connectionString =
"Driver={Microsoft Text Driver (*.txt; *.csv)};DefaultDir=" + Path;//eg:- Path= "c:\Data"

//Void Open(string ConnectionString,string UserID,string Password,int Options)
connection.Open(connectionString, "", "", (int)ConnectModeEnum.adModeUnknown);

string strSql = string.Format("Select * FROM {0} ORDER BY Name,{1} desc", FileName, FieldToSort); // filename="SampleData.csv" , FieldToSort = "ID"

object obj;
//Recordset Execute(string CommandText,out object RecordsAffected,int Options)
Recordset rs = connection.Execute(strSql, out obj, (int)CommandTypeEnum.adCmdText);

DisplayData(rs);

rs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
{
if(connection != null && connection.State != (int)ConnectionState.Closed)
connection.Close();
}
}

private void DisplayData(Recordset rs)
{
string strToDisplay = string.Empty;

//show field names
for(int i=0 ; i<rs.Fields.Count ; i++)
{
strToDisplay += rs.Fields[i].Name + ",";
}

strToDisplay = strToDisplay.Trim(',') + Environment.NewLine;

//recordsetobject.GetString (StringFormat, NumRows, ColumnDelimiter, RowDelimiter, NullExpr)
strToDisplay += rs.GetString(StringFormatEnum.adClipString,-1,",",Environment.NewLine,string.Empty);

textBox1.Text = strToDisplay;

}

Friday 2 January 2009

2008 Walk through

Well!!! main event that happend in 2008 was my marriage,on Aug/17/2008 and it was an arranged marriage.The arragement factor (or unexpected factor) involved in my marriage might have disappointed my female fans :-) (just kidding!!!!!).

First step to Blogging world.

Today I have created new blogging site with the help of internet giant google.