Wednesday, November 9, 2011

Load matfiles


Load the required files from a directory


clc
matDIR = '/.../matfiles/';
% workDIR = '/Volumes/3TB/.../AquaLand20/';
files = dir(matDIR);

% Remove the '.DS_Store' from the list
if strcmp(files(3).name, '.DS_Store')
files(3) = [];
end


% count =3;
row = 1;
for count= 3:length(files)

FNamebase=files(count).name;

inDIR =[matDIR, FNamebase];

if exist(inDIR)>0

load([inDIR ]);
time(row) = toc;
iter(row) = j-1;

disp(['Loaded! ',FNamebase]);

row = row+1
end
end

Tuesday, November 8, 2011

Using Imagemagick shell command to crop figures

How to crop figure and save as png.
This is useful for cropping similar figures located in a folder.

Copy the code, save as cropfig.sh
and then run the cropfig.sh in your terminal...

#!/bin/bash
width=1800;
height=1680;
x_offset=502;
y_offset=40;
filelist=`ls | grep '.png'`
for image_file in $filelist
do
preextensionfilename=`convert $image_file -format "%t" info:`
convert $image_file -crop ${width}x${height}+${x_offset}+${y_offset} \
${preextensionfilename}_${width}x${height}.png
done


Thursday, November 3, 2011

Remove the .DS_Store from the file list

Sometimes, working on the filelist is troublesome because of the .DS_Store

WhereAqua = pwd;

files = dir(WhereAqua);

% Remove the '.DS_Store' from the list
if strcmp(files(3).name, '.DS_Store')
files(3) = []
end


There is another way too!
fileLIST = dir;
N = length(fileLIST); % fileLIST.name
 status = mkdir(pwd, 'hdfClass'); 

if exist('.DS_Store','file')
! rm .DS_Store
fn =  fileLIST(4).name;
else
fn =  fileLIST(3).name;  

-->

Monday, September 12, 2011

To replace the un-necessary strings in filename

Somehow, the filenames had infections with the extra '%E7%E7htm'.
What surprises me is that not all files had the same error.
So, I wrote a simple code to get rid of the extra characters in the filename/ extension.



% To replace   '%E7%E7htm' by 'htm'

% fn = '2Oct_09.%E7%E7htm'
list = dir;

jj = 1;
while jj < length ( list)
    fn = list(jj,1).name;
    [pathstr, name, ext] = fileparts(fn)
    if  strcmp(ext,'.%E7%E7htm') % ~list(jj,1).isdir
        
%         if strcmp(fn(9:15),'%E7%E7h')
          newfn=  strrep(fn, '%E7%E7h', 'h');
%         end
          system([ 'mv ' fn,' ' newfn])
        
%       disp('asdf')  
    end
    jj = jj+1;
end


Wednesday, September 7, 2011

Add Waving Nepali Flag widget in blogger







This post is about how to add a widget to blogspot blogs.


The code is:
<form method="POST" action="http://www.blogger.com/add-widget">
<input type="hidden" name="widget.title" value="NP Flag"/>
<input type="hidden" name="widget.content" value="<a style='display:scroll; position:fixed; bottom:100px; left:24px;' href='#'><img src='http://i1202.photobucket.com/albums/bb377/nabinkm/nepalflag.gif' alt='np flag' width='75' height='100' border='0' /></a>"/>
<input type="hidden" name="widget.template" value="<data:content/>" />
<input type="hidden" name="infoUrl" value="http://www.nabinkm.com"/>
<input type="hidden" name="logoUrl" value="#"/>
<input type="submit" name="go" value="Add NP flag"/>
</form>


Sunday, September 4, 2011

Twitter Follow badge for blogger with Nepal.gif Flag

Cool GIF flag in blogspot blog with twitter follow button

Add the following code in the html code of your blog before </body> tag

<!-- twitter follow badge by go2web20 -->
<script src='http://www.go2web20.net/twitterfollowbadge/1.0/badge.js' type='text/javascript'/>
<script charset='utf-8' type='text/javascript'><!--
tfb.account = 'nabinkm';
tfb.label = 'follow-me';
tfb.color = '#2f3192';
tfb.side = 'r';
tfb.top = 136;
tfb.showbadge();
--></script>
<!-- end of twitter follow badge -->



Now insert the html at any place in the body. For blogger blogs, I find it easy to add html element and add it there.



<a style="display:scroll;position:fixed;bottom:100px;left:1px;" href="http://www.twitter.com/nabinkm" target="_blank"><img height="97" style="border:0;" src="http://i.imgur.com/t2Iha.jpg" /></a>
<a href="http://www.twitter.com/nabinkm"> @nabinkm </a>



<a style="display:scroll;position:fixed;bottom:100px;left:24px;" href="http://www.twitter.com/nabinkm" target="_blank"><img style="border:0;" src="https://lh4.googleusercontent.com/-EIrgWSiVvwk/Taezn19w38I/AAAAAAAAHqU/zOrSSKtKrOs/s155/nepalflag.gif" height="100" width="75" /></a>


Wednesday, August 31, 2011

Hex code for Colormap, matlab

I wanted to set the color code for the table to match with that of the figure.

colormap(jet(33))
labels = {'0','1','2','3'};
lcolorbar(labels,'fontweight','bold')
map2 = colormap; map2( 1, : ) = 1; colormap(map2)
cmap = colormap; % cmap nicely puts colormap into 3 col data

perCmap= (single(round(cmap.*255))); % convert to 255 scale
% You can use one of these options:
colorcell = ['rgb(' num2str(perCmap(1,1)), ',', num2str(perCmap(1,2)), ',', num2str(perCmap(1,3)) ')']

colorcell = ['#' (dec2hex(perCmap(1,1))), dec2hex(perCmap(1,2)), dec2hex(perCmap(1,3)) ]
% the second worked best for me

% I then set it to fid1 for txt file, which I was writing.
<td style="color:#ffffff" bgcolor="%s">
% where %s was the string set as colorcell for open fid fprintf(fid1,'<h1>%s <td/h1>', htmlH1);


Thursday, July 21, 2011

Diff Tool Mac

I have to say FileMerge is one of the best diff tool I have seen.
Just change the folder and do opendiff for two desired files.
I wanted to see the changes I made on two files by using diff, I was immediately sold!

The tool is already included in the system if you have Xcode environment set up

opendiff Jul20.m Jul21.m

Tuesday, July 19, 2011

Changing the bash prompt mac

My bash prompt looked long and clumsy. So I wanted it short.

FIrst I opened the bash profile


nano .bash_profile
Then I added:
export PS1="My-Mac2:"
Write out, and voila!

Thursday, July 14, 2011

Using simple unix command line in Matlab

I was not aware that I could use the unix commands in the matlab command.
This can be done by having prompt in the command:

>> !rm *.png
>> !rm *.gif
>> !rm *.fig
>> !rm *.mat

Wednesday, July 6, 2011

Close mac Terminal after you are done

The exit command:
It works if the following setting is done:
Terminal
>Preferences
>Settings
>Shell
>Prompt before closing: never
or
> When the shell exits:
select: close if the shell exited cleanly

The following kills the terminal:

killall Terminal

So, if I want to kill the terminal after I am done, I will simply add:
killall Terminal
instead of kill

Wednesday, June 22, 2011

Installing Spell Checker in TeXworks (Mac)

Installing spell checker in TeXworks is going to be straightforward after I write this note.
The dicttionary for TeXworks is located at:
/Users/gajab/Library/TeXworks/dictionaries
where gajab is your username.



One easy source of dictionaries is the OpenOffice.org project, which uses the same spelling engine. There is a list of available dictionaries at http://wiki.services.openoffice.org/wiki/Dictionaries (see the All Language Packs download, or links to individual language dictionaries). Note that TeXworks only uses the spelling dictionaries (*.dic and *.aff) for each language ...

  • So I downloaded the dictionary file from
    http://extensions.services.openoffice.org/en/dictionaries
    It is located currently at:
    http://extensions.services.openoffice.org/en/project/en_US-dict
  • However, the file is saved as .oxt.  I simply renamed the package as a zip file
    en_US.oxt >> en_US.zip
    and unzipped the package (well, double click and rename along with the extension. It warns, but you can change the extension). It worked!!
    The package contains:
    META-INF description.xml en_US.aff info
    README_en_US.txt dictionaries.xcu en_US.dic
  • WE only need .dic and .aff files. So I copied it to the library folder for the TeXworks.



cp ~/Downloads/en_US/en_US.aff /Users/gajab/Library/TeXworks/dictionaries
cp ~/Downloads/en_US/en_US.dic /Users/gajab/Library/TeXworks/dictionaries

The dictionary worked nicely after I restarted the TeXworks.

Guide to LaTeX (4th Edition)More Math Into LaTeX, 4th EditionLaTeX: A Document Preparation System (2nd Edition)

Wednesday, May 25, 2011

Full Screen Figure matlab

Full Screen Figure/Image.

scrsz = get(0,'ScreenSize');

% Create figure
h = figure('Position',[1 scrsz(4) scrsz(3) scrsz(4)]);


Related to:
http://usefulcodes.blogspot.com/2011/05/saving-big-matlab-figure-with-subplots.html

Monday, May 23, 2011

Saving Big Matlab Figure with Subplots

MATLAB Advanced GUI DevelopmentSaving Big Figure with Subplots can sometimes be tricky as the titles can be messy and the screen resolution might not help.

Here is what fixed my full-screen plot/image without destroying the titles.

fneps=[Figname,'.eps'];
set(gcf,'PaperPositionMode','auto')
print('-depsc2','-r200',fneps);
The format could be eps or png or fig... as preferred.

Friday, May 20, 2011

Making pretty Figures in Matlab

I had a function calling these with gca option.
h = figure;
%plot

set(h,'LineWidth',1.12);
x_label = 'Class';
y_label = 'Range';
fig_title = char(DATAVAR);
% DATAVAR = variables{j}; from the loop and string list created as a cell structure.
% variables = {'Var1', 'Var2'} etc.
fig_title = regexprep(fig_title, '_', ' ');% To remove the underscores

xlabel(x_label, 'FontSize',[16], 'FontWeight' ,'bold');
ylabel(y_label, 'FontSize',[16], 'FontWeight' ,'bold');
newTitle = [fig_title]; % get the title from File Name (fn)
title(newTitle, 'FontSize',[20], 'FontWeight' ,'bold' );
set(gca,'LineWidth',[2.0], 'FontSize',[14],'FontWeight','bold')

Monday, May 16, 2011

Kile on Mac

Somehow the Macports evaporated out of my system.
So, I end up reinstalling the Kile via macports.

export PATH=/opt/local/bin:/opt/local/sbin:$PATH
$ sudo port selfupdate

$ port upgrade outdated
Reinstalled KILE:
$ sudo port install kile


I think installing one of the program last week kicked it out... I will need to verify that.

Saturday, May 14, 2011

Date and Time in File Name matlab

Printing Months name as string for data analysis.
This also checks the existence of the file with the extension ".ext"; say dec_09.ext.


months={'jan','feb','mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'};
for iyear=5: 9

year_st = num2str(iyear,'%2.2i');

for i=1:length(months)
fn=[months{i} '_' year_st '.ext'];
if exist(fn, 'file')

disp(fn)
else
continue
end
end
end

Tuesday, May 10, 2011

Two instances of Matlab in Mac

Typing this on the terminal does the trick!!
$ /Applications/MATLAB_R2010b.app/bin/matlab

Running two instances of matlab: Does it slow down the performance?
Will see...

Monday, May 9, 2011

Saving Matlab Figures as EPS

Saving files as eps is slightly troublesome.

One could use various options. However, for my case, there was cropping in saveas option.

% Print to ps file
Figname = 'TestFigure'
fneps=[Figname,'.eps'];
set(gcf,'PaperPositionMode','auto')
print('-depsc2','-r200',fneps);
% print('-dpsc2','-zbuffer','-r200',fneps);
% saveas(gca,Figname,'psc2');

Friday, May 6, 2011

Cleaning my Keyboard

Let me be litttle funny and produce my own garbage.

I would like to clean my keyboard and see what text does that produce. The work is inspired by the infinite monkey theorem and the dust accumulated on my keyboard.
Start cleanup...
---------
jjjjjjjjjjjjjhjhjhjhjhjhjhjhjhhjhjkjkkknnnmnmnmnmnbnbbbvvvvgvgvgvgfgcffcfcfcfcfcfxxxdxdxxxzzszszszszssawawawawqawqqqqQq q 2qwq3w3w3w4ew4e4ererrdrrrrtrftftyyuyuhuhuhuiuiujiijioioioopopoplplplpl[;[;[[;;];];]']']'
'lmn kn bivcygctfxreszeedsxttgvjb ngyff6tr5rdsxzxewa2wq 1QArdcub omn l,'.,'./.mpn-vccxtdxz5eszewa4esz on ],
/ pob uc x
/?///./....// 1 1///?';lmm, 1q 21 1`12q2q23w3w43e4e4e5r5r5r6t6t7t7yy8u8u9iu9i0i0o-o-p=\]\
.m v ctzeqq 1 1 1` 1` 112-009u8764567lmloiuiucxrrseswasasdxgvchbjm , , ./...,;,;;;l[;[;[';\







---------
End of cleanup


Note: When I was blowing the dust on the keyboard, the force was not sufficient to push any keys and those are un noticed in the process. About 40 microgram of dust was collected in due process.

Thursday, May 5, 2011

Accessing variables as string (matlab)

Easy access to the variables via evaluation command


variables = {'a', 'b','c'}
a = 22;
% operations
eval(variables{1})+2
% works

Wednesday, May 4, 2011

Pie chart with label and percentage


Wanted to have a pie chart with class label as well as the percentage.
This does the job.


class = [Count1 Count2 Count3 Count4];

b = (round(class/sum(class)*100))
% explode = [0,0,1]; % well you can explode it
h=pie(class, {['Class 1 (',num2str(b(1)),'%)'],['Class 2 (',num2str(b(2)),'%)'], ['Class 3 (',num2str(b(3)),'%)'],['Class 4 (',num2str(b(4)),'%)']});
% pie(class,{'Class 1 ','Class 2','Class 3 ', 'Class 4 '})
% well try pie3 too

Monday, May 2, 2011

Extract href link item from the html source matlab

Extract href link item from the html source by using matlab.
The result is that the link is saved in a txt file.


%%
% Search for number of string matches per line.
% replace "href" tag by "ctrl H + manual line break".. in doc ..
% makes life easy
home
clc
filename = 'textsrc.txt';
literal = ' <a href="';

fid = fopen(filename, 'rt');
bbase = 'dsave2'
fid_sh = fopen([bbase '.txt'],'w');

y = 0;
jj = 1;
while feof(fid) == 0
tline = fgetl(fid);

matches = findstr(tline, literal);
num = length(matches);
if num > 0
y = y + num;
% fprintf('%s\n',tline);
fprintf(fid_sh, '%s \n', tline);
end
jj = jj+1;
end
fclose(fid);
fclose(fid_sh)
% this file generates the output on the screen which needs to be copied and
% saved as
% dsave2.txt
% Which will be further operated by refinestr.m

MATLAB for Engineers (2nd Edition)MATLAB Primer, Eighth EditionDigital Signal Processing Using MATLAB

Creating HTML files with favorite pages loaded in matlab

I have saved the pages with sublink such as
http://usefulcodes.blogspot.com/2011/03/how-to-block-website-in-macos.html
http://usefulcodes.blogspot.com/search/label/matlab
etc...

The first part of the link (below) is the home page. The file structure is saved as text array so that textread function in Matlab reads the content as the cell structure. The structure can be accessed iteratively by file{j}.




filename = 'dsave1.txt';
j = 1;

file = textread(filename, '%s', 'delimiter', '\n', ...
'whitespace', '');

for j = 1:length(file)
link = ['http://www.urlurl.com/' file{j}]
% end

file_name = [num2str(j) '.htm'];

fid =fopen(file_name,'wb'); %_id=%s will do the job
fprintf(fid, '<html><head><title>1</title></head><body>');

fprintf(fid, '<iframe name="FRAME" src="%s" width="1040" height="700" frameborder="0" scrolling="no"></iframe></body></html>',link);

fclose(fid);

j = j+1;

end

Just open with Chrome. Tada!

Monday, April 18, 2011

Open Firefox web browser in Matlab Mac

Wanted to open a web browser from Matlab.
This works for Firefox. Similar things should do for chrome... Lets see.


webDIR = '/Applications/Firefox.app/Contents/MacOS/firefox';
system([webDIR, ' www.usefulcodes.blogspot.com'])

OR,
open -a Firefox
Consulting
http://www.google.com/support/forum/p/Chrome/thread?tid=68ef8a58f86e1fe2&hl=en

But not working for chrome.


Getting Started with MATLAB: A Quick Introduction for Scientists and EngineersDigital Image Processing Using MATLAB, 2nd ed. 

Thursday, April 7, 2011

Code Box for Blogger

Thanks to
http://www.tutzone.org/2009/04/professional-code-box-for-bloggers.html
I have new code block for code section

CODE GOES HERE

Making matlab avi Video with ordered file list


Easy way to display the month-year as string.
Which can then be used to prepare a video out of the file list.


video_obj = VideoWriter('rotation2.avi');
video_obj.FrameRate = 1;

open(video_obj)
months={'Jan','Feb','Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'};
for iyear=5: 9

year_st = num2str(iyear,'%2.2i');
for i=1:length(months)
fn=[months{i} '_' year_st '.fig'];
disp(fn)
Figtitle = strrep(fn,'_','');

set(gca,'FontSize',30);
eval(sprintf('title(''%s'',''FontSize'',[28],''FontWeight'',''bold'')',Figtitle));
pause(0.1)
F = getframe(fig);
writeVideo(video_obj,F);
pause(0.5)
end
close(video_obj);

end

Friday, April 1, 2011

L, One and I in programming scripts


l1I Courier
l1I Tribuchet
l1I Arial
l1I Helvetica

l1I Times

How many times you have stumbled because of these great bad designs of the fonts?
What is your default font for writing codes?
l1I

Thursday, March 31, 2011

Automating file operations in matlab excluding the directories

Automating the work in directory with tree structure is fun. You can leave it overnight and get the output the next day.
However, hidden files/folders can be troublesome.
Specially these:
.
..
and .DS_Store (in mac)
or other set up stuffs

for jj = 1:length(fileList)
if fileList(jj).isdir
% do not operate the file
else
% call the function to operate on it * see footnote

end
%% footnote:

fileTARGET = '/Users/.../monthly';
saveTARGET ='/Users/.../figuresSAVE'
% Do the regular stuff
cd(fileTARGET)
% Do the regular stuff: train
fileLIST = dir;
N = length(fileLIST); % fileLIST.name
fn = fileLIST(4).name;
% fn='asdf.ext';
disp(fn)
trainME(fn) % train the network: takes data and trains
%save the figures here
cd(saveTARGET);
% savefile = fn;
save('savetrained.mat', '-mat', 'net'); % save the network... JIC
% cd(fileTARGET);
% cd(saveTARGET); instead, we can feed the folder structure into function making the code more general see below:
saveFIG(fileLIST, fileTARGET, saveTARGET, net); 

% save the plotted figures; as the target directories and save target directories are taken as input, it is more general for its usages


%%%%%%%%%%

I have also found a better way of working on it:



for jj = 1:length(fileLIST)
fn = fileLIST(jj).name;
[pathstr, name, ext] = fileparts(fn);
if strcmp(ext, '.hdf')
% do not operate the file
% else
disp(['Working on : ', fn])
end
end

Monday, March 21, 2011

Click and get the co-ordinates of a plot

Getting the co-ordinates of the desired points in matlab plot can be tricky.
ginput useful!
Do:

[x,y] = ginput(n)

and hit enter/spacebar to exit if no n is specified.

Thursday, March 10, 2011

How to block website in MacOS

Say wanted to block facebook...

 Do
 sudo pico /etc/hosts

enter: into the file
 127.0.0.1 facebook.com

 and save out ctrl+O; ctrl+x

refresh cache
 sudo dscacheutil -flushcache

Friday, March 4, 2011

Thursday, March 3, 2011

Using MacPorts and Porticus

Macports (http://www.macports.org/) is awesome, except that it installed stuffs in wierd places so that I could not run netcdf properly. Now I have done it manually.
Came across the GUI for it:

Looks good!
http://porticus.alittledrop.com/index.html
Except that it is also unable to update stuffs!
:(

Wednesday, March 2, 2011

Installing Kile on Mac

 I find it easy to use macport.

  • Simply go to macport site to download the disk image (dmg) for macport. (http://www.macports.org/install.php or google macport kile)
  • do sudo port install kile
    BOOM
  • It will install all the dependencies and kile itself.  

Read setting path after installing macports:
http://usefulcodes.blogspot.com/2011/05/kile-on-mac.html

Thursday, February 24, 2011

Running command line programs in Mac

Type in textwrangler

#!/bin/bash
cd /applications/IDV
./runIDV

Saved it as runIDV.command in home

Right click on the item and then create alias. Move the alias to the Applications folder on the dock.

Bingo!

Wednesday, February 23, 2011

Map of the Earth on Matlab topo.mat

It is nice and handy to know that the map of the earth  is available on Matlab.

load topo
contour(topo,[0,0],'k')


Topo contour plot in matlab.

The Blue marble!

The cool 3D map is obtained after running the code from:
with cdata on to sphere.

 Remote Sensing and Image InterpretationRemote Sensing of Vegetation: Principles, Techniques, and ApplicationsAn Introduction to Ocean Remote Sensing

Sunday, February 20, 2011

Matlab Answers Central

Matlab has opened up with answers. This is awesome as this can serve as a place for users to interact and post the problems, and possibly the solutions.
They have some system of having points as in yahoo answers, but other than feeling better that the poster helped to solve the problem, I am not sure what does that score mean.

http://www.mathworks.com/matlabcentral/answers/