need help
Can any one have any idea ..........about mouse programming.....in MATLAB.................In 3 Dimensions.......means 3D point generation/line/curve etc.......using mouse.
Post Matlab code snippets. Sort by tags, people, people and tags, etc.. Brought to you by XTargets - Consulting & Application devlopment.
|
New to Matlab Snippets? Matlab Snippets is a public code repository. You can easily add code to your personal collection of code snippets, categorize your code snippets with keywords (known as 'tags'), and share your snippets via this site.
need helpCan any one have any idea ..........about mouse programming.....in MATLAB.................In 3 Dimensions.......means 3D point generation/line/curve etc.......using mouse. Snippets is being retiredHave moved to a new blog engine and a new url.http://xtargets.com/blog This site will stay live for historical purposes but no new content will be added. Radio Frequency Kill Switch is On ( Acer Wireless Stops Working )Today I opened up my three year old acer 3002wlmi laptop to vacuum all the dust out of it in a vain attempt to make the fan a little quieter and the box to run a little less hot.The vacuuming semi successful I turn the box back on, running Ubuntu 7.10 (Feisty), only to find that the wireless networking is not recognized. The horror of life without internet suddenly struck me. However I found in my bag of bits and old Netgear USB wireless stick. I didn't have much faith in it working but I plugged it in and it worked immediately. However how to get my built-in wireless working. I ran dmesg and found the following. [ 124.663287] ipw2200: Radio Frequency Kill Switch is On: [ 124.663290] Kill switch must be turned off for wireless networking to work. After nosing around the newsgroups I ended up running the following commands. mod ipw2200 sudo rmmod ipw2200 sudo modprobe fsam7400 sudo su sudo modprobe ipw2200 echo_ "1" > /proc/driver/wireless/radio exit Not sure if I needed all the above. The line starting "echo" is definitely needed as that is what is started the wireless radio again. Now all is working again but the fan still runs loud and the box is hot. Update The above all gets cleared on reboot. To make it permanent do. sudo echo_ fsam7400 >> /etc/modules sudo echo_ options fsam7400 radio=1 >> etc/modprob.d/options Liquid Planner : Project Management ToolI have been looking for a project management tool for ages, one that doesn't make me curl up inside and want to die and one that helps my team get stuff done rather than waste their time.Finally stumbled across Liquid Planner which turns out to be an amazing little tool. The features that I really like are * Range estimation for tasks. * Category vs Project views. LP takes a novel approach to planning. Instead of giving a single point estimate. ie this task will take 10d to complete I estimate that the task will take between 8d and 12d to complete. This uncertainty is percolated up into the estimates for the rollup tasks and eventually to the estimate for the entire project. Range estimates fit my brain better than single point estimates and I think they make me more honest. The second feature I like is that there are two views of the system. The category view allows you to do a functional decomposition of the project. Containers can be nested and are navigable via a tree view. So this view is great for design and requirements capture. The "project view" is again a tree view but items higher up on the screen and containers represent milestones. Containers are nested so you can model intermediate deliverables or sprints within you greater plan. The project view is orthogonal to the category view and this is important because when designing a view you want to see the functional layout. When planning you want to see the order in which things need to be delivered. This has solved my one gripe about other tools I see. They are either good for requirements capture or good for scheduling but never for both. Scheduling works quite well. It performs resource leveling and supports precedes and depends on dependencies. Scheduling is done in the background and you are notified by an icon when the scheduling is finished and you should refresh the screen. On the downside, here in Europe the site is a bit sluggish but to be fair they are still in beta and the devs seems quite responsive on the forums. As it is in beta it is currently free to sign up to but will eventually cost about $25 USD per user per month. Fair enough if it saves me an hour a month in time. As a final note the site is a Ruby On Rails application which may excite or turn some people off depending on their religion :) Matlab onCleanup fatally flawed?Matlab 2008a provides a new functiononCleanup Loren Shure writes about it here http://blogs.mathworks.com/loren/ However I think the class is fatally flawed. As I read the Matlab documentation the implementation of onCleanup is fatally flawed and I don’t think anybody should use it unless some things can be clarified. According to the Matlab documentation ‘the lifecycle of an object ends *sometime* between the time its variable is no longer used inside the function and the end of the function’ The implementation of onCleanup seems to rely on a subtly different interpretation of object lifecyle. ‘the lifecycle of an object ends at the end of the function within which it’s last reference is lost’ This means the following example function y = run4 % run4 processes an image file. [fid,C] = openImageFile4(); blocksize = 100; y = []; while something dat = fread(fid,count); y = doSomething(y,dat); something = update(something); end is broken. According to Matlab spec C could be deleted any time after it appears in the line [fid,C] = openImageFile4(); thus deleting the file handle whilst it was being used. It looks like a classic race condition problem. To be safe you could rewrite the code function y = run4 % run4 processes an image file. [fid,C] = openImageFile4(); blocksize = 100; y = []; while something …dat = fread(fid,count); …y = doSomething(y,dat); …something = update(something); end C; But somehow I see the Matlab optimiser at some time in the future stripping out such dead code and rendering the trick useless anyway. Stylistically it is also not obvious to a reader of the code what C is being used for and it’s inclusion in the code could easily be deleted by an eager maintainer unless the ode is accompanied by copious documentation. There are however neater ways to solve the same problem in other languages. The Python way: http://docs.python.org/whatsnew/pep-343.html with open(’/etc/passwd’, ‘r’) as f: for line in f: print line lexical scoping is used to clarify the required lifetime of the file handle f. As well if any exception is thrown from within the block the file is also closed. The Ruby way: File.open ‘/etc/passwd’ do |f| f.each_line do |l| puts l end end Very similar to the python way and again there is no requirement by the user to provide any cleanup or close functionality. In case of normal block termination or in the event of an error the open function will *always* close the file handle when the block terminates. The onCleanup functionality could also be dealt with by adding an ensure keyword to the Matlab language as has Ruby and Python. function do_open(file, flags, action) fid = fopen(file, flags) try action(fid) ensure fclose(fid) end end Notice there is no catch above. We don’t want to catch an error we just want to *ensure* that we cleanup if there is an error or not. Any error is propagated to code further upstream to handle. The ensure can be substituted with a catch and rethrow but is a bit uglier as you need to write code to handle closing the file if and if not an error occurs. Using do_open in Matlab would be like do_open(’/etc/passwd’, ‘r’, @body) function body(fid) read(fid, 10) function_with_error() end As is obvious the function definition is kind of superfluous and would be nicer with some kind of multi line anonymous function do_open(’/etc/passwd’, ‘r’ ) @(fid) read(fid, 10) function_with_error() end C++ lambdasI've just noticed that the C++0x standard has just accepted lambda functions as part of the upcoming standard. So you will be able to dostd::vector<int> someList; int total = 0; std::for_each(someList.begin(), someList.end(), <>(int x) : [&total] (total += x)); std::cout << total; It actually comes in two forms, an expression form where a return value is not required for one line quickies and a function form which is surrounded by curly braces and requires a return statement. Note that Matlab only allows the expression form. Multi line anonymous functions are not possible which is quite strange and limiting. See to matlab lambda functions c++0x by bradphelan on Mon Mar 10 21:38:06 +0000 2008 Matlab 2008aI don't do much Matlab these days but it is nice to see that release 2008a is out with the much waited for object oriented additions.It is definitely something that will make programming Matlab much easier for larger applications and do away with many of the hacks which I have illustrated myself on this website. However I am not sure I like the verbosity of the OO features. For example there are provisions for - attributes - events - methods - listeners whereas in Ruby you can make do with just instance variables and methods, the rest being sorted out with meta programming tricks. Mentioning metaprogramming I don't see any facility for this within the documentation though it is probably there under the hood. Also not sure why you are restricted to creating classes in files. It would be neat and generally usefully to be able to create classes at the command line and/or multiple classes per file as is possible in Ruby/Python. I also noted a boo boo in the documentation. Some doc writer claims that Matlab is weakly typed, when in fact they mean dynamically typed as opposed the to statically typed. Matalb is strongly and dynamically typed whereas C/C++ is weakly and statically typed. A simple example from the Mathworks home page classdef BankAccount < handle properties (Hidden) AccountStatus = 'open'; end % The following properties can be set only by class methods properties (SetAccess = private) AccountNumber AccountBalance = 0; end % Define an event called InsufficientFunds events InsufficientFunds end methods function BA = BankAccount(AccountNumber,InitialBalance) BA.AccountNumber = AccountNumber; BA.AccountBalance = InitialBalance; % Calling a static method requires the class name % addAccount registers the InsufficientFunds listener on this instance AccountManager.addAccount(BA); end function deposit(BA,amt) BA.AccountBalance = BA.AccountBalance + amt; if BA.AccountBalance > 0 BA.AccountStatus = 'open'; end end function withdraw(BA,amt) if (strcmp(BA.AccountStatus,'closed')&& BA.AccountBalance < 0) disp(['Account ',num2str(BA.AccountNumber),' has been closed.']) return end newbal = obj.AccountBalance - amt; BA.AccountBalance = newbal; % If a withdrawal results in a negative balance, % trigger the InsufficientFunds event using notify if newbal < 0 notify(BA,'InsufficientFunds') end end % withdraw end % methods end % classdef See Mathworks for more information. Demangling C++ type information at run timeHere's a nice way to print the type of an object to an ostream. Handy during debugging when you have nested template horrors shriveling your brain.#include <cxxabi.h> template <typename T> struct TypeInfo { friend std::ostream & operator <<(std::ostream & os, TypeInfo<T> t){ const std::type_info & ti = typeid(T); int status; char * realname = abi::__cxa_demangle(ti.name(), 0, 0, &status); os << realname; free(realname); return os; } }; use as std::cout << TypeInfo<std::vector<std::vector<int> > >() << std::endl will print std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > Convert a string to anything using a function.Not sure where this would be usefull but was playing around with the C++ cast operator and came up with this gem. Allows you to assign a string to any type in the declaration.#!c++!# int a = strconv("1"); struct strconv { std::string s; Convert(std::string s):s(s){ } template <typename T> operator T ( ){ std::istringstream ss(s); T t; ss >> t; return t; } }; Syntax Highlighting For C++ Template Expansion Errors In VimTired of looking at horrific unreadable template expansion errors when using c++. A little sprinkle of syntax highlighting makes the mess a little easier on the eyes.Drop this snippet in your .vimrc function! CppSyn() syntax cluster xOperators contains=xOperator1,xOperator2,xOperator3,xOperator4,xOperator5,xOperator6 syntax region xBlock1 start=/\(\w\+\)\(::\w\+\)*</ end=/>/ contains=iBlock1 syntax region iBlock1 start=/</ms=s+1 end=/>/me=e-1 contained containedin=xBlock1 contains=xBlock2 syntax region xBlock2 start=/\(\w\+\)\(::\w\+\)*</ end=/>/ contains=iBlock2 syntax region iBlock2 start=/</ms=s+1 end=/>/me=e-1 contained containedin=xBlock2 contains=xBlock1 " ensure we don't match Foo::Bar::operator<< as the beginning of a " template syntax match xOperator1 "\(\w\+::\)*operator<<" " Create some sexy colors hi xBlock1 guifg=#44ff44 hi xBlock2 guifg=#ff4444 hi iBlock1 guifg=#4444ff hi iBlock2 guifg=#ff44ff endf au FileType qf call CppSyn() Now run make from within VIM and your gcc/g++ error log will look like candy. select line by mouse motionI'm trying to catch the lines the user selected by the mouse MOTION (i.e. NOT by clicking) WindowButtonMotionFcn and WindowButtonUpFcn are defined only on the figure that mean I can have only the "current point" value (but not current object for example..) and thats doesn't help me for identify the line the user have selected.anyone can help me??? thanks dalhad@gmail.com C++ foreach idiomIsn't the STL wonderfull .... until you have started using languages such as Python and Ruby. In C++ to iterate over a STL container you have to write ick like this.vector<int> v; //Put some stuff in v vector<int>::iterator it = v.begin(); for (;it != it.end(); it++ ){ cout << *it; } Now I say that is clunky. STL iterator syntax is great when you want to do complex things but nasty when you want to do simple things. Have a look at this code which does exactly the same as the above code. vector<int> v; //Put some stuff in v for(each<int> it; it.in(v);){ cout << *it; } Much nicer. And here is the implementation of each. Obviously to achieve this magic you have some performance penalty as I need to take advantage of a class with virtual functions. Anybody who can see a way to improve this please contact me. template <typename T> class iter{ public: virtual void inc() = 0; virtual T & operator*() = 0; virtual bool end() = 0; virtual ~iter() { } }; template <typename T> class each{ iter<T> * mIter; bool mIsEnd; T * mCurrent; public: template <class C> class iterImpl : public iter<T> { typename C::iterator mIt; typename C::iterator mEnd; public: iterImpl(C & c):mIt(c.begin()), mEnd(c.end()){ } void inc(){ ++mIt; } T & operator*(){ return *mIt; } bool end(){ return mIt == mEnd; } }; each(): mIter(NULL),mIsEnd(false),mCurrent(NULL) { } T & operator*(){ return *mCurrent; } template <class C>bool in(C & container){ if (mIter==NULL){ mIter = new iterImpl<C>(container); } mCurrent = &**mIter; mIter->inc(); if (mIsEnd){ return false; } mIsEnd = (mIter->end()); return true; } }; Stripping constness using c++ templatesI've been working a lot with C++ in my new job. This means getting to grips once more with the STL, generic programming and templates. The more I dig into templates the more Alice In Wonderland it gets. We were playing around with a reference counting smart pointer. The basic template was ::template <class ReferencePtr> class AutoPtr { ... } where ReferencePtr is the class of the pointer we wish to hold manage. For example Foo * foo = new Foo; AutoPtr<Foo> ptr = foo; That was all well and good until we tried const Foo * foo = new Foo; AutoPtr<const Foo> ptr = foo; This failed to compile. When we investigated we found parts of AutoPtr had declarations such as one of the constructors. AutoPtr(const ReferencePtr * ref); The problem with this is that if ReferencePtr is expanded as "const Foo" then the constructor expands to. AutoPtr(const const Foo * ref); which results in a compilation error. How to fix this? We need a const stripping template class to get to the raw type Foo without it's const. Here is a version template <C> struct ConstStripper { typedef C type_name; }; template <C> struct ConstStripper<const C> { typedef C type_name; }; now we redefine our constructor as AutoPtr(const typename ConstStripper<ReferencePtr>::type_name * ref); now whether ReferencePtr is const Foo or just Foo const ConstStripper<ReferencePtr>::type_name will always expand to just Foo. Neat! Now isn't that a constipated solution. Digital pen / Mouse inputCan any one give me code for inputing data from digital pen / mouse which i need for handwritig recognitionIntegers as HEX in IRBWant to display integers as hex in IRB without messing with printf. Add this snippet to your .irbrcclass Integer @@as_hex = false def self.toggle_base @@as_hex = ! @@as_hex end alias old_inspect inspect def inspect if @@as_hex sprintf("0x%x", self) else old_inspect end end def to_hex sprintf("0x%x", self) end end Then you can do the following in your IRB session $ irb >> 255 => 255 >> 25 => 25 >> Integer.toggle_base => true >> 255 => 0xff >> 25 => 0x19 >> Reactive Programming In RubyIn reactive programming a set of variables with dependencies are created. When a variable is modified it notifies all other variables that it depends on to update their values.The below simple class Reactive implements one such solution to this problem. a = react 10 b = react 20 c = react(a,b){ |x,y| x + y } d = react(b,c){ |x,y| x + y } vars = {:a=>a,:b=>b,:c=>c,:d=>d} vk = [:a, :b, :c, :d] report = proc do vk.each do |k| puts "#{k} #{vars[k].value}" end end puts " Initial value of variables " report[] a.value = 40 puts " New value of variables " report[] generates Initial value of variables a 10 b 20 c 30 d 50 New value of variables a 40 b 20 c 60 d 50 Implementation class Reactive # On change of value dependants are notified # of updates def value=(val) @value=val @depends.each do |d| d.notify end end # Add d as a listener def notify_me d @depends << d end # Get the cached value unless the # dirty flag has been set then # recalc the value from the block def value if @block && @dirty argv = [] @args.each do |a| if a.respond_to? :value argv << a.value else argv << a end end @value = @block.call *argv end @dirty=false @value end # Notify this object that at # least one dependant has changed. def notify @dirty=true end # Init the class with the dependant # reative variables and a block to # evaluate to compute the value # of this object. def initialize *args, &block @depends = [] if block_given? @args = args @block = block @args.each do |a| a.notify_me self end else # This is a literal @value = *args end @dirty=true end end def react *args, &block Reactive.new *args, &block end Textual Regular ExpressionsRegular expressions can be a bit cryptic. I had a short go at implementing a DSL for Ruby regular expressions. It is by no means complete but it gives ideas for further work.class RexpAtom def initialize str @str = str @m = 1 end def * m @m = m end def to_s if @m == 1 return @str end if @str !~ /^\(.*\)$/ && @str.length != 1 str = ( "(" + @str + ")" ) else str = @str + "" end case @m when :many str = str + '*' when :opt str = str + '?' else if @m.is_a? Range str = str + "{#{@m.min},#{@m.max}}" else str = str + "{#{@m}}" end end str end def | other @str << "|" other end end class RexpBuilder def initialize &blk @s = [] self.instance_eval &blk end def [](literal=nil, &blk) l(literal, &blk) end def _ literal=nil, &blk s = '' if block_given? s << "(" end if block_given? o = RexpBuilder.new &blk s << o.to_s elsif literal if literal.is_a? String s << literal.to_s elsif literal.is_a? Range s << ( "[" + literal.min.to_s + "-" + literal.max.to_s + "]" ) elsif literal.is_a? Enumerable s << "(" s << literal.join('|') s << ")" else s << literal.to_s end end if block_given? s << ")" end a = RexpAtom.new s @s << a a end def to_s @s.collect do |s| s.to_s end.join "" end end class Rexp def self.rexp &blk RexpBuilder.new(&blk).to_s end end And an example of use a = Rexp.rexp do _('hello') * 2 _ do _('x') | _('y') * :opt end * (1..3) _('x') | _('y') | _(1..3) | _('a'..'z') | _([1,2,3]) end puts a generates (hello){2}(x|y?){1,3}x|y|[1-3]|[a-z]|(1|2|3) IRB and issuing shell commands with pipes.If you wish to issue pipe two commands together in bash then it is easy.ls /bin | grep grep generates bzegrep bzfgrep bzgrep egrep fgrep grep zegrep zfgrep zgrep but how to do this neatly in IRB How about like require './shell.rb' Sh.ls("/bin").grep("grep") using the library module Sh class Command def initialize(cmd, *args) @cmd = cmd @args = args @io = nil end def inspect to_s end def to_str to_s end def to_s call str = @io.read @io.close str end def | other call other.call(@io) end def method_missing(name, *args) self | Command.new(name, *args) end def call (io=nil) # The @io object can only be assigned # once return self if @io command = @cmd.to_s + " " + @args.join(" ") if io # We need a new process # and a pipe to connect the # this command to the previous # command in the chain. rd, wr = IO.pipe if fork # Parent wr.close else # Child rd.close begin # Reconnect the STDIN of the # new process to the io parameter $stdin.reopen(io) IO.popen command do |f| while txt = f.read(4096) wr.write txt end end rescue Errno::EPIPE # Ignore the broken pipe # cause the other process # has thrown away the pipe # earlier than we used outs ensure wr.close end exit end @io = rd else # This command is executed standalone. @io = IO.popen command end self end end def self.method_missing (name, *args) Command.new(name, *args) end end SCons Magic GlobSCons is a great tool for building projects in C/C++. However I ran across a little problem the other day. I was using glob to get lists of source files from the source directory to then build into a library.However some of those sources were auto-generated. Previously to get around this I would maintain a list of the auto generated sources and add them to the list of those discovered by glob. This was ugly but worked until I decided to change the build directory for the library. Then glob didn't work at all. Why was this? Well, it is because SCons copies the SConscript file to the build directory before executing it. glob then works on the build directory and as there are no files there yet it returns nothing. There must be an elegant way to solve this and it turns out after a day of banging around there sort of is. On the SCons wiki there are a few solutions to the problem none of which seemed to work when I tried them so I rolled my own based upon what I could glean from the wiki. However before I show the code I want to list my requirements. I want a Glob function that will return a list of files matching a pattern. The list must include files that - permanently exist in the source/build directory. - may be generated in the source/build directory from previously executed SCons build declarations. This will be powerful because our Glob will return lists of files some of which may not actually exist but that SCons has promised to build. This will allow us to avoid the messy problem of carrying around lists of files. Now the code import fnmatch import glob import os # Magic glob retrieves all files that # exist in the source directory or will # be generated by previously defined # rules. # # Arguments # # patten - glob pattern with no path information # dir - the relative dir to search for the # pattern. # # XXX Need to implement recursive search as # well as absolute directories def Glob( pattern, dir = "."): # Fix up root relative directories if dir.startswith ("#"): dir = os.path.join (str (Dir ("#")), dir[1:]) def search_static(node, pattern, base = ''): dir = str(node) base = str(base) if not base.endswith('/') and base != '': base = base + "/" results = [] files = glob.glob(os.path.join(dir, pattern)) for r in files: if r.startswith (base): r = r[len(base):] results.append(r) return results def search_dynamic(node, pattern, base = ''): results = [] node = Dir(node) node_s = str(node) base = str(base) if not base.endswith('/') and base != '': base = base + "/" l = len (node_s) for f in node.all_children(): f = str(f) if fnmatch.fnmatch (f, pattern): # append the src to the results if f.startswith(base): f = f[len(base):] results.append (f) # This seems to be necessary to refresh the # object after a call to all_children() node.clear() return results def is_abs(path): return os.path.abspath(dir) == dir # The current build directory bd = Dir(".") build_dir_s = str(bd) build_dir_l = len(build_dir_s) # The current source directory sd = bd.srcnode() src_dir_s = str(sd) src_dir_l = len(src_dir_s) results = [] if is_abs(dir): # Only search the static and # dynamic for this directory # and return the absolute # paths results += search_static(dir, pattern) results += search_dynamic(dir, pattern) else: # Search the static and dynamic # for both build and source # and return relative paths # Build dir bd = Dir(".") bds = str(bd) bd_search = os.path.join(bds, dir) # Source dir sd = bd.srcnode() sds = str(sd) sd_search = os.path.join(sds, dir) # results += search_static (bd_search, pattern, bd ) results += search_static (sd_search, pattern, sd ) results += search_dynamic (bd_search, pattern, bd) results += search_dynamic (sd_search, pattern, sd) # Fix up ./ prefixes res = [] for r in results: if r.startswith ('./'): r = r[2:] res.append (r) # Uniquify the list files = {} for f in res: files[f] = None res = [ f for f in files.iterkeys() ] return res Return('Glob') You can get a handle to this function in your SConstruct file by Glob = SConscript('scons_glob.py') #auto generate a file Command ("foo.c", "touch foo.c") #get a list of files files = Glob ("*.c") Will return "foo.c" even if it has not been built yet.
|
|