Friday, March 13, 2015

[matlab] relocate an object in the figure window

function movePosition(myh,myfrac,opt)
% move an object to a new location relative to current axes
% usage:
%      movePosition(obj-handle,fraction,opt)
%             opt: 'x' ==> x-coordiante is given in fraction of xlim
%                    'y' ==> y-coordiante is given in fraction of ylim
%                  'xy' ==> both x,y-coordiante is given in fraction
%                                (could be a 2-element vector)
% http://scriptdemo.blogspot.ca

if nargin~=3
   help movePosition
   return
end
if numel(myh)>1
   for nh=1:numel(myh)
       movePosition(myh(nh),myfrac,opt);
   end
   return
end
if ~ishandle(myh)
   error('need a valid object handle')
end

oriPos=get(myh,'position');
if isempty(oriPos)
    error('no position attribute is available')
end
if isnumeric(opt)
   oriPos(1)=myfrac;
   oriPos(2)=opt;
else
   switch lower(opt)
    case {'x'}
        cXLim=get(gca,'xlim');
        oriPos(1)=oriPos(1)+myfrac*(cXLim(2)-cXLim(1));
    case {'y'}
        cYLim=get(gca,'ylim');
        oriPos(2)=oriPos(2)+myfrac*(cYLim(2)-cYLim(1));
    case {'xy'}
        if numel(myfrac)==1
            myfrac=[myfrac myfrac];
        end
        cXLim=get(gca,'xlim');
        oriPos(1)=oriPos(1)+myfrac(1)*(cXLim(2)-cXLim(1));
        cYLim=get(gca,'ylim');
        oriPos(2)=oriPos(2)+myfrac(2)*(cYLim(2)-cYLim(1));
    otherwise
        error(['unknown opt: ',opt])
   end
end
set(myh,'position',oriPos);

No comments:

ShowCalendar