Wednesday, November 18, 2009

Read Text with Mixed Data and Delimiter (Matlab)

In Matlab, if we have to read text with mixed data (numerical and alphanumerical data) and the text has delimiter, we can use textscan.

for example:

if the text file contains the following data:

<TICKER>,<PER>,<DTYYYYMMDD>,<TIME>,<OPEN>,<HIGH>,<LOW>,<CLOSE>,<VOL>,<OPENINT>
HU___1985G,D,19841203,000000,0.7180,0.7250,0.7160,0.7245,221,165
HU___1985G,D,19841204,000000,0.7275,0.7290,0.7240,0.7254,75,220
HU___1985G,D,19841205,000000,0.7190,0.7250,0.7165,0.7230,267,390

Then we can write the code like:

fid = fopen(filename);
c = textscan(fid, '%s %s %d %s %n %n %n %n %n %n' ,'delimiter', ',', 'headerLines', 1);
fclose(fid);

Here the delimiter is ',' and the function will skip 1 line of header.

Saturday, September 26, 2009

Matlab, String, Char and Array

Create Array of String

Creating array of String is different from creating array of character. For creating array of String, we need to use cell instead.

For example

variable1 = [];
variable1(1) = 'Dec';

The second line will give an error: "Subscripted assignment dimension mismatch" because the variable1 has 1x1 dimension, while 'Dec' will be treated as 1x3 char

For doing this we will use cell instead

variable1 = {};
variable1{1} = 'Dec';

to call it use '{}' too.

Create Array of String from Array of Char
Use cellstr(array_of_char)

For example if we have variable p, where:
>> p

p =

1985G
1985G
1985G
1985G
1985G

>>size(p)

ans =

5 5


.then

>>cellstr(p)

ans =

'1985G'
'1985G'
'1985G'
'1985G'
'1985G'

>>size(cellstr(p))

ans =

5 1

Tuesday, July 21, 2009

Matlab - Add a new cell

If you know in advance how many results you will generate you can use:

c = cell(1, 100);
for i = 1:100
% code that generates v
c{i} = v;
end

if not then you can use:

c = {};
% "some for loop here that creates v"
c{end+1} = v;
end

Saturday, July 11, 2009

.NET - How to find the index of a datarow

int position = DataTable.Rows.IndexOf(DataRow);