Legend Location 'Best', but still in corner if possible - matlab

I want to set the Location of my legend to 'Best' (like legend('y1','y2','Location','Best')) so the legend doesn't collide with my lines, but at the same time, I would prefer to have it in a corner if that's possible with no data collision. Is there a way of implementing this?

In case anyone's interested in this, I wrote a function based on #S.. answer that does, what I wanted to achieve. Here's the code:
function setPositionCornerBest( figureHandle )
%Sets the Location of the legend of the figure that is referenced by figureHandle to one of the Corners if there is no data in the Corners. Otherwise it sets it to 'Best'
h = figureHandle;
figObjects = get(h,'Children');
legHandle = findobj(figObjects,'Tag','legend');
axHandle = findobj(figObjects,'Type','axes','-and','Tag','');
lineHandle = findobj(figObjects,'Type','line','-and','Parent',axHandle);
axPos = get(axHandle,'Position');
LimX = get(axHandle,'XLim');
LimY = get(axHandle,'YLim');
xScaling = (LimX(2)-LimX(1))/axPos(3);
yScaling = (LimY(2)-LimY(1))/axPos(4);
locCell = {'NorthWest','NorthEast','SouthEast','SouthWest'};
ii = 1;
interSecFlag = true;
while (interSecFlag) && (ii<=4)
set(legHandle,'Location',locCell{ii});
legPos = get(legHandle,'Position');
x(1) = LimX(1)+(legPos(1)-axPos(1))*xScaling;
x(2) = x(1);
x(3) = LimX(1)+(legPos(1)+legPos(3)-axPos(1))*xScaling;
x(4) = x(3);
x(5) = x(1);
y(1) = LimY(1)+(legPos(2)-axPos(2))*yScaling;
y(2) = LimY(1)+(legPos(2)+legPos(4)-axPos(2))*yScaling;
y(3) = y(2);
y(4) = y(1);
y(5) = y(1);
for jj = 1:numel(lineHandle)
xline = get(lineHandle(jj),'XData');
yline = get(lineHandle(jj),'YData');
[xInter ~] = intersections(x,y,xline,yline);
if numel(xInter) == 0
xInterFlag(jj) = 0;
else
xInterFlag(jj) = 1;
end
end
if all(xInterFlag==0)
interSecFlag = false;
end
ii = ii + 1;
end
if interSecFlag
set(legHandle,'Location','Best');
end
end

I don't have a complete answer, only a sketch. However, you could try to first set the legend in a corner
a=legend('y1', 'y2', 'Location', 'NorthEast')
and then obtain its position
get(a,'Position')
You can convert this position to coordinates and simply test whether your lines cross any border of the legend using
http://www.mathworks.com/matlabcentral/fileexchange/11837-fast-and-robust-curve-intersections
.If this is the case, try another corner, until there is no corner left. In that case, use 'Best'.

Related

How to find Orientation of axis of contour in matlab?

I want to find Orientation, MajorAxisLengthand MinorAxisLength of contour which is plotted with below code.
clear
[x1 , x2] = meshgrid(linspace(-10,10,100),linspace(-10,10,100));
mu = [1,3];
sigm = [2,0;0,2];
xx_size = length(mu);
tem_matrix = ones(size(x1));
x_mesh= cell(1,xx_size);
for i = 1 : xx_size
x_mesh{i} = tem_matrix * mu(i);
end
x_mesh= {x1,x2};
temp_mesh = [];
for i = 1 : xx_size
temp_mesh = [temp_mesh x_mesh{i}(:)];
end
Z = mvnpdf(temp_mesh,mu,sigm);
z_plat = reshape(Z,size(x1));
figure;contour(x1, x2, z_plat,3, 'LineWidth', 2,'color','m');
% regionprops(z_plat,'Centroid','Orientation','MajorAxisLength','MinorAxisLength');
In my opinion, I may have to use regionprops command but I don't know how to do this. I want to find direction of axis of contour and plot something like this
How can I do this task? Thanks very much for your help
Rather than trying to process the graphical output of contour, I would instead recommend using contourc to compute the ContourMatrix and then use the x/y points to estimate the major and minor axes lengths as well as the orientation (for this I used this file exchange submission)
That would look something like the following. Note that I have modified the inputs to contourc as the first two inputs should be the vector form and not the output of meshgrid.
% Compute the three contours for your data
contourmatrix = contourc(linspace(-10,10,100), linspace(-10,10,100), z_plat, 3);
% Create a "pointer" to keep track of where we are in the output
start = 1;
count = 1;
% Now loop through each contour
while start < size(contourmatrix, 2)
value = contourmatrix(1, start);
nPoints = contourmatrix(2, start);
contour_points = contourmatrix(:, start + (1:nPoints));
% Now fit an ellipse using the file exchange
ellipsedata(count) = fit_ellipse(contour_points(1,:), contour_points(2,:));
% Increment the start pointer
start = start + nPoints + 1;
count = count + 1;
end
orientations = [ellipsedata.phi];
% 0 0 0
major_length = [ellipsedata.long_axis];
% 4.7175 3.3380 2.1539
minor_length = [ellipsedata.short_axis];
% 4.7172 3.3378 2.1532
As you can see, the contours are actually basically circles and therefore the orientation is zero and the major and minor axis lengths are almost equal. The reason that they look like ellipses in your post is because your x and y axes are scaled differently. To fix this, you can call axis equal
figure;contour(x1, x2, z_plat,3, 'LineWidth', 2,'color','m');
axis equal
Thank you #Suever. It help me to do my idea.
I add some line to code:
clear
[X1 , X2] = meshgrid(linspace(-10,10,100),linspace(-10,10,100));
mu = [-1,0];
a = [3,2;1,4];
a = a * a';
sigm = a;
xx_size = length(mu);
tem_matrix = ones(size(X1));
x_mesh= cell(1,xx_size);
for i = 1 : xx_size
x_mesh{i} = tem_matrix * mu(i);
end
x_mesh= {X1,X2};
temp_mesh = [];
for i = 1 : xx_size
temp_mesh = [temp_mesh x_mesh{i}(:)];
end
Z = mvnpdf(temp_mesh,mu,sigm);
z_plat = reshape(Z,size(X1));
figure;contour(X1, X2, z_plat,3, 'LineWidth', 2,'color','m');
hold on;
% Compute the three contours for your data
contourmatrix = contourc(linspace(-10,10,100), linspace(-10,10,100), z_plat, 3);
% Create a "pointer" to keep track of where we are in the output
start = 1;
count = 1;
% Now loop through each contour
while start < size(contourmatrix, 2)
value = contourmatrix(1, start);
nPoints = contourmatrix(2, start);
contour_points = contourmatrix(:, start + (1:nPoints));
% Now fit an ellipse using the file exchange
ellipsedata(count) = fit_ellipse(contour_points(1,:), contour_points(2,:));
% Increment the start pointer
start = start + nPoints + 1;
count = count + 1;
end
orientations = [ellipsedata.phi];
major_length = [ellipsedata.long_axis];
minor_length = [ellipsedata.short_axis];
tet = orientations(1);
x1 = mu(1);
y1 = mu(2);
a = sin(tet) * sqrt(major_length(1));
b = cos(tet) * sqrt(major_length(1));
x2 = x1 + a;
y2 = y1 + b;
line([x1, x2], [y1, y2],'linewidth',2);
tet = ( pi/2 + orientations(1) );
a = sin(tet) * sqrt(minor_length(1));
b = cos(tet) * sqrt(minor_length(1));
x2 = x1 + a;
y2 = y1 + b;
line([x1, x2], [y1, y2],'linewidth',2);

Matlab: PDE toolbox, get length of each element on the boundary

I setup and meshed a domain using Matlab's PDE toolbox. Along the boundary, is there someway to get the length of each element of the mesh? And the flux in the normal direction? (the bc are Dirichlet)
Edit:
See example code
RMax = 20;
RL = 1;
RU = 0.5;
HN = 5;
HL = 2;
HTT = 3;
HU = 1.5;
VL = -150;
p = [RL,0;RL,HN;0,HN+HL;0,HN+HL+HTT;RU,HN+HL+HTT+HU;RMax,HN+HL+HTT+HU;RMax,0];
t = [1;1;0;1;1;0;0];
v = [VL;VL;0;0;0;0;0];
dx = 0.5;
dy = 0.5;
bc = cell(size(t));
for i = 1:length(t)
if t(i) == 0
bc{i} = {'u', v(i)};
elseif t(i) == 1
bc{i} = {'g', v(i), 'q', 1};
else
error('Unrecognized boundary condition type.')
end
end
model = createpde;
gd = [2; size(p,1); p(:,1) ; p(:,2)];
ns = char('domain')';
sf = 'domain';
g = decsg(gd,sf,ns);
geometryFromEdges(model,g);
generateMesh(model, 'Hmax', min([dx,dy])/3, 'MesherVersion','R2013a');
for i = 1:size(bc,1)
applyBoundaryCondition(model, 'Edge', i, bc{i}{:});
end
u = assempde( model , 'x' , 0 , 0 );
pdemesh(model)
Edit: 2015-12-17 18:54 GMT
There are 2 points in the e shown at 1 and 2 in the figure below. I want to know the coordinate of 3 so I know which direction is into the domain.
You can answer your first question by using meshToPet to convert to [P,E,T] form:
[p,e,t] = meshToPet(model.Mesh);
x1 = p(1,e(1,:)); % x-coordinates of first point in each mesh edge
x2 = p(1,e(2,:)); % x-coordinates of second point in each mesh edge
y1 = p(2,e(1,:)); % y-coordinates of first point in each mesh edge
y2 = p(2,e(2,:)); % y-coordinates of second point in each mesh edge
% Plot first points of mesh edge
plot(x1,y1,'b.-',x1(1),y1(1),'go',x1(end),y1(end),'ro');
% Euclidean distance between first and second point in each edge
d = sqrt((x1-x2).^2+(y1-y2).^2);
I'm assuming you just want the lengths of the mesh edge/boundary. You can use similar methods to get the lengths of every single triangle using the t matrix.
As far as flux goes, there's pdecgrad. I think the following may work:
...
c = 'x';
u = assempde(model, c, 0, 0);
[p,e,t] = meshToPet(model.Mesh);
[cgxu,cgyu] = pdecgrad(p,t,c,u);

Matlab - Failures of function to detect collisions between line segments and circle

Many questions exist already covering how to detect collisions between a line segment and a circle.
In my code, I am using Matlab's linecirc function, then comparing the intersection points it returns with the ends of my line segments, to check that the points are within the line (linecirc assumes an infinite line, which I don't have/want).
Copying and adding some sprintf calls to the linecirc function shows that it is calculating points as intended. These seem to be being lost by my function.
My code is below:
function cutCount = getCutCountHex(R_g, centre)
clf;
cutCount = 0;
% Generate a hex grid
Dg = R_g*2;
L_b = 62;
range = L_b*8;
dx = Dg*cosd(30);
dy = 3*R_g;
xMax = ceil(range/dx); yMax = ceil(range/dy);
d1 = #(xc, yc) [dx*xc dy*yc];
d2 = #(xc, yc) [dx*(xc+0.5) dy*(yc+0.5)];
centres = zeros((xMax*yMax),2);
count = 1;
for yc = 0:yMax-1
for xc = 0:xMax-1
centres(count,:) = d1(xc, yc);
count = count + 1;
centres(count, :) = d2(xc, yc);
count = count + 1;
end
end
for i=1:size(centres,1)
centres(i,:) = centres(i,:) - [xMax/2 * dx, yMax/2 * dy];
end
hold on
axis equal
% Get counter for intersected lines
[VertexX, VertexY] = voronoi(centres(:,1), centres(:,2));
numLines = size(VertexX, 2);
for lc = 1:numLines
segStartPt = [VertexX(1,lc) VertexY(1,lc)];
segEndPt = [VertexX(2,lc) VertexY(2,lc)];
slope = (segEndPt(2) - segStartPt(2))/(segEndPt(1) - segStartPt(1));
intercept = segEndPt(2) - (slope*segEndPt(1));
testSlope = isinf(slope);
if (testSlope(1)==1)
% Pass the x-axis intercept instead
intercept = segStartPt(1);
end
[xInterceptionPoints, yInterceptionPoints] = ...
linecirc(slope, intercept, centre(1), centre(2), L_b);
testArr = isnan(xInterceptionPoints);
if (testArr(1) == 0) % Line intersects. Line segment may not.
interceptionPoint1 = [xInterceptionPoints(1), yInterceptionPoints(1)];
interceptionPoint2 = [xInterceptionPoints(2), yInterceptionPoints(2)];
% Test if first intersection is on the line segment
p1OnSeg = onSeg(segStartPt, segEndPt, interceptionPoint1);
p2OnSeg = onSeg(segStartPt, segEndPt, interceptionPoint2);
if (p1OnSeg == 1)
cutCount = cutCount + 1;
scatter(interceptionPoint1(1), interceptionPoint1(2), 60, 'MarkerFaceColor', 'r', 'MarkerEdgeColor', 'k');
end
% Test if second intersection point is on the line segment
if (interceptionPoint1(1) ~= interceptionPoint2(1) || interceptionPoint1(2) ~= interceptionPoint2(2)) % Don't double count touching points
if (p2OnSeg == 1)
cutCount = cutCount + 1;
scatter(interceptionPoint2(1), interceptionPoint2(2), 60, 'MarkerFaceColor', 'r', 'MarkerEdgeColor', 'k');
end
end
end
end
% Plot circle
viscircles(centre, L_b, 'EdgeColor', 'b');
H = voronoi(centres(:,1), centres(:,2));
for i = 1:size(H)
set(H(i), 'Color', 'g');
end
end
function boolVal = onSeg(segStart, segEnd, testPoint)
bvX = isBetweenOrEq(segStart(1), segEnd(1), testPoint(1));
bvY = isBetweenOrEq(segStart(2), segEnd(2), testPoint(2));
if (bvX == 1 && bvY == 1)
boolVal = 1;
else
boolVal = 0;
end
end
function boolVal = isBetweenOrEq(end1, end2, test)
if ((test <= end1 && test >= end2) || (test >= end1 && test <= end2))
boolVal = 1;
else
boolVal = 0;
end
end
It creates a hexagonal grid, then calculates the number of crossings between a circle drawn with a fixed radius (62 in this case) and a specified centre.
The scatter calls show the locations that the function counts.
Implementing sprintf calls within the if(p1OnSeg == 1) block indicates that my function has chosen fictitious intersection points (although it then deals with them correctly)
if (interceptionPoint1(1) > -26 && interceptionPoint1(1) < -25)
sprintf('p1 = [%f, %f]. Vx = [%f, %f], Vy = [%f, %f].\nxint = [%f, %f], yint = [%f, %f]',...
interceptionPoint1(1), interceptionPoint1(2), VertexX(1,lc), VertexX(2,lc), VertexY(1,lc), VertexY(2,lc),...
xInterceptionPoints(1), xInterceptionPoints(2), yInterceptionPoints(1), yInterceptionPoints(2))
end
Outputs
p1 = [-25.980762, 0.000000]. Vx = [-25.980762, -25.980762], Vy = [-15.000000, 15.000000].
xint = [-25.980762, -25.980762], yint = [0.000000, 0.000000]
A picture shows the strange points.
Sorry for the very long question but - why are these being detected. They don't lie on the circle (displaying values within a mylinecirc function detects the intersections at around (-25, 55) and (-25, -55) or so (as an infinite line would expect).
Moving the circle can remove these points, but sometimes this leads to other problems with detection. What's the deal?
Edit: Rotating my grid pattern created by [Vx, Vy] = voronoi(...) and then removing points with very large values (ie those going close to infinity etc) appears to have fixed this problem. The removal of 'large' value points seems to be necessary to avoid NaN values appearing in 'slope' and 'intercept'. My guess is this is related to a possible slight inclination due to rotation, coupled with then overflow of the expected intercept.
Example code added is below. I also edited in Jan de Gier's code, but that made no difference to the problem and so is not changed in the question code.
%Rotate slightly
RotAngle = 8;
RotMat = [cosd(RotAngle), -sind(RotAngle); sind(RotAngle), cosd(RotAngle)];
for i=1:size(centres,1)
centres(i,:) = centres(i,:) - [floor(xMax/2) * dx, floor(yMax/2) * dy]; %Translation
centres(i,:) = ( RotMat * centres(i,:)' ); %Rotation
end
% Get counter for intersected lines
[VertexX, VertexY] = voronoi(centres(:,1), centres(:,2));
% Filter vertices
numLines = size(VertexX, 2);
newVx = [];
newVy = [];
for lc = 1:numLines
testVec = [VertexX(:,lc) VertexY(:,lc)];
if ~any(abs(testVec) > range*1.5)
newVx = [newVx; VertexX(:,lc)'];
newVy = [newVy; VertexY(:,lc)'];
end
end
VertexX = newVx';
VertexY = newVy';
numLines = size(VertexX, 2);
Still appreciating answers or suggestions to clear up why this is/was occuring.
Example values that cause this are getCutCountHex(30, [0,0]) and ...(35, [0,0])
I cant reproduce your problem, but the thing I did notice is that your onSeg() function might be wrong: it returns true if the testpoint lies in the rectangle with two of the four corner points being segStart and segEnd.
A function that returns true iff a point is on (or more accurate: close enough to) the line segment (segStart,segEnd) could be:
function boolVal = onSeg(segStart, segEnd, testPoint)
tolerance = .5;
AB = sqrt((segEnd(1)-segStart(1))*(segEnd(1)-segStart(1))+(segEnd(2)-segStart(2))*(segEnd(2)-segStart(2)));
AP = sqrt((testPoint(1)-segEnd(1))*(testPoint(1)-segEnd(1))+(testPoint(2)-segEnd(2))*(testPoint(2)-segEnd(2)));
PB = sqrt((segStart(1)-testPoint(1))*(segStart(1)-testPoint(1))+(segStart(2)-testPoint(2))*(segStart(2)-testPoint(2)));
boolVal = abs(AB - (AP + PB)) < tolerance;
end
an approach that I found in one of the anwers here: Find if point lays on line segment. I hope that solves your problem.

Using Heat Equation to blur images using Matlab

I am trying to use the PDE heat equation and apply it to images using Matlab. The problem i am having is that the image isn't blurring , it is just going white. Also, I am getting different results from the rest of the class who is using Maple.
Here is the code:
% George Lees Jr.
% Heat equation
clear,clc;
dx = 1;
dy = 1;
dt = .025;
%dt/(dx*dx)
t = 0;
time = 3;
T_old = imread('tulipgray.jpg');
T_temp=T_old;
[m,n,k] = size(T_temp);
%colormap gray;
%imagesc(T_temp);
%imshow(T_old);
T_new = T_temp;
T_new=ind2gray(T_new,colormap);
%T_new(:,50)=0;
%T_old(1,70)
%imagesc(T_new);
%diff_x = dt/(dx*dx)
%diff_y = dt/ (dy*dy)
%time = 0;
while t < time
for i = 2:1:m-1
for j = 2:1:n-1
T_new(i,j) = T_temp(i,j) + dt*(T_temp(i+1,j) -2*T_temp(i,j) + T_temp(i-1,j)) + dt*(T_temp(i,j+1)-2*T_temp(i,j) + T_temp(i,j-1));
t = t+dt;
T_temp(i,j) = T_new(i,j);
end
end
end
figure
imshow(T_new)
Yeah the image just gets whiter
There's 2 issues with your code:
1) you're incrementing the time counter after each individual pixel instead of after doing the whole image
2) you need to do the calculations on floating points values, not integers. dt is small, so the values from the RHS of the equation are <1
Fixed code should look something like this
clear,clc;
dt = 0.025;
time = 3;
T_old = imread('rice.png');
T_temp=double(T_old);
[m,n,k] = size(T_temp);
T_new = double(T_temp);
T_new=ind2gray(T_new,colormap);
while t < time
for i = 2:1:m-1
for j = 2:1:n-1
T_new(i,j) = T_temp(i,j) + dt*(T_temp(i+1,j) -2*T_temp(i,j) + T_temp(i-1,j)) + dt*(T_temp(i,j+1)-2*T_temp(i,j) + T_temp(i,j-1));
end
end
T_temp = T_new;
t = t+dt;
imshow(uint8(T_new))
getframe;
end

Code for a multicolumn legend in Matlab

I have designed an application called CLegend, which allows to build a multicolumn legend, whose code is
function CLegend(hax,numcol,Ley)
%# Inputs
% hax : handle of the axes object to which belongs the legend
% numcol: number of columns for the legend
% Ley: text strings (labels) for the legend
set(hax,'Units','normalized','Position',[0.1 0.1 0.8 0.8]);
set(hax,'Units','characters');
posAx = get(hax,'Position');
insAx = get(hax,'TightInset');
[legend_h,object_h] = legend(hax,Ley,'Units','characters','Location',...
'South','Orientation','vertical');
posl = get(legend_h,'Position');
numlines = length(Ley);
if (numlines<numcol)
numcol = numlines;
end
numpercolumn = ceil(numlines/numcol);
if (mod(numlines,numpercolumn) == 0)
numcol = numlines/numpercolumn;
end
l = zeros(1,numlines);
a = zeros(1,numlines);
h = zeros(1,4);
for j=1:numlines
h = get(object_h(j),'Extent');
l(j) = h(3);
a(j) = h(4);
set(object_h(j),'Units','characters');
end
lmax = posl(3)*max(l);
hmax = posl(4)*max(a);
hLine = object_h(numlines+1);
xdata = get(hLine, 'xdata');
dx = xdata(2)-xdata(1);
di = 2;
sheight = hmax;
height = hmax*numpercolumn-sheight/2;
line_width = dx*posl(3);
spacer = xdata(1)*posl(3);
delta1 = spacer + line_width + spacer + lmax;
delta2 = line_width + spacer + lmax + spacer;
delta3 = lmax + spacer + line_width + spacer;
factx = 1/(posl(3)*numcol);
facty = 1/(hmax*numpercolumn);
width_l = numcol*delta1;
set(legend_h, 'Position', [posAx(1) + 0.5*(posAx(3)-width_l) posl(2) ...
width_l numpercolumn*hmax]);
col_ind = -1;
row_ind = -1;
j = 0;
for i=1:numlines,
if strcmpi(orient,'horizontal'),
if mod(i,numcol)==1,
row_ind = row_ind+1;
end
col_ind = mod(i,numcol)-1;
if col_ind == -1,
col_ind = numcol-1;
end
else
if numpercolumn==1 || mod(i,numpercolumn)==1,
col_ind = col_ind+1;
end
row_ind = mod(i,numpercolumn)-1;
if row_ind == -1,
row_ind = numpercolumn-1;
end
end
if (i==1)
linenum = i+numlines;
else
linenum = linenum+di;
end
labelnum = i;
set(object_h(linenum), 'ydata',facty*[height-row_ind*sheight ...
height-row_ind*sheight]);
set(object_h(linenum), 'xdata', factx*[spacer + j*delta2 ...
spacer + j*delta2 + line_width]);
set(object_h(linenum+1), 'ydata',facty*(height-row_ind*sheight));
set(object_h(linenum+1), 'xdata', factx*(spacer+line_width/2));
set(object_h(labelnum), 'Position', [j*delta3+spacer*2+line_width ...
height-row_ind*sheight]);
if (mod(i,numpercolumn)== 0)
j = j + 1;
end
end
opl = get(legend_h,'OuterPosition');
set(hax, 'Position',[posAx(1) posAx(2)+opl(4) posAx(3) posAx(4)-opl(4)]);
set(legend_h, 'OuterPosition',[opl(1) (posAx(2)-insAx(2))/2 opl(3) opl(4)]);
set([hax,legend_h],'Units','normalized');
end
I have problems with it. I have tried it with a more complicated code but similar to this one that appears below.
function qq
fh = figure('Units','characters');
GrapWin = uipanel ('Parent',fh,'Units','characters','title','Graphic',...
'Position',[135 5 120 40]);
haxes = axes('Parent',GrapWin,'Units','normalized','Position',[0.1 0.1 0.8 0.8]);
PanVD = uipanel('Parent',fh,'Units','characters','Position',[55 5 30 10],...
'title','Dependent Variable');
VDlh = uicontrol('Parent',PanVD,'Style','listbox','Units',...
'normalized','Position',[0 0 1 1],'String',{'X','Y','Z'},'Value',1,...
'Callback',#VDLhCallback);
T = 0:pi/100:2*pi;
X = sin(T);
xlabel(haxes,'Time');
title(haxes,'Sine Function');
plot(haxes,T,X);
CLegend(haxes,3,{'Var X'});
function VDLhCallback (src,evt)
value = get(VDlh,'Value');
switch value
case 1
title(haxes,'Sine Function');
plot(haxes,T,X);
CLegend(haxes,3,{'Var X'});
case 2
title(haxes,'Cosine Function');
Y = cos(T);
plot(haxes,T,Y);
CLegend(haxes,3,{'Var Y'});
case 3
Z = tan(T);
title(haxes,'Tangent Function');
plot(haxes,T,Z);
CLegend(haxes,3,{'Var Z'});
end
end
end
It happens something that I do not understand because the first time that CLegend is called the legend appears not centered (respect to axes) but the following callings through the listbox options it does is centered.
Other problem that occurs is that if I delete the command line
set(haxes,'Units','normalized')
then, although the legend is centered, the axes appear with a reduced size.
I also have found that the first time Clegend is calles, the position of the axes (variable posAx) is different from the following callings (in which posAx is always the same).
I have thought that when the units were changed, the position of the object was not changed but this problem arises doubts inside my mind.
In the Figure Properties documentation, it is said of Unit
This property affects the CurrentPoint and Position properties. If you
change the value of Units, it is good practice to return it to its
default value after completing your computation so as not to affect
other functions that assume Units is the default value.
Can it explain your problems?
After a lot of proofs, I have found that my problem was the resizing of the figure. The first time CLegend was called the figure window had its original size. The following calls of CLegend happened with the figure windows maximized.