I have a plot in Matlab as following, I want to add some parameters to the figure like the figure which I have added. Could you help me with how to solve that? Thank you so much.
delta = 0.5;
I1=2;
I2 =4;
T = 5;
tau = 0.5;
b = 8;
a = 6;
c = 8;
d = 4;
t = [0:0.001:5];
y =(a-b*exp(-tau*t)).*(t>=0 & t<delta*T )+(-d+c*exp(-tau*(t-delta*T))).*(t>=delta*T & t<=T);
plot(t,y , 'b', 'LineWidth',1.8)
hold on
x = [0:0.01:12];
max = 4*ones(1,1201);
min = -2*ones(1,1201);
z = 0*ones(1,1201);
plot(x,max , '--g', 'LineWidth',1)
hold on
plot(x,min , '--g', 'LineWidth',1)
plot(2,min , '--g', 'LineWidth',1)
plot(x,z , 'k', 'LineWidth',1.7)
axis([0 6 -4 6])
I think this code might generate something close for what you are looking. It is important to say that the arrows for x and y can be added using the same "annotation command".
delta = 0.5;
I1=2;
I2 =4;
T = 5;
tau = 0.5;
b = 8;
a = 6;
c = 8;
d = 4;
t = [0:0.001:5];
y =(a-b*exp(-tau*t)).*(t>=0 & t<delta*T )+(-d+c*exp(-tau*(t-delta*T))).*(t>=delta*T & t<=T);
plot(t,y , 'b', 'LineWidth',1.8,'DisplayName',"Data")
% Change the y limits
ylim([-4 6])
hold on
% %% Set the horizontal lines and its name in the y axis
% MAX LINE - Create a yline Cte along the plot
hLine = yline(4);
hLine.LineWidth = 1;
hLine.Color = "g";
hLine.LineStyle = "--";
hLine.DisplayName = "Max Line";
% MIN LINE - Create a yline Cte along the plot
hLine = yline(-2);
hLine.LineWidth = 1;
hLine.Color = "g";
hLine.LineStyle = "--";
hLine.DisplayName = "Min Line";
% Zero LINE - Create a yline Cte along the plot
hLine = yline(0);
hLine.LineWidth = 1.7;
hLine.Color = "k";
hLine.LineStyle = "-";
% Change the "name" in the y axis
hAxis = gca;
% Get index
% - when y is equal to "Max" in this case 4
% - when y is equal to "MIN" in this case -2
idx = hAxis.YTick == 4;
hAxis.YTickLabel{idx} = 'X';
idx = hAxis.YTick == -2;
hAxis.YTickLabel{idx} = 'Y';
% %% Set the vertical lines and its name in the x axis
% Delta LINE - Create a xline Cte along the plot
hLine = xline(2.5);
hLine.LineWidth = 1;
hLine.Color = "k";
hLine.LineStyle = "-";
% MIN LINE - Create a yline Cte along the plot
hLine = xline(4);
hLine.LineWidth = 1;
hLine.Color = "k";
hLine.LineStyle = "-";
% Add the notes
annotation('textbox',[.55 .2 .3 .3],"String","Delta",...
'FitBoxToText','on','LineStyle','none')
annotation('textbox',[0.8 0.2 .3 .3],"String","A",...
'FitBoxToText','on','LineStyle','none')
The previous code will generate the next figure.
Related
I am working on a project and my aim is to color and 20 randomly generated lines of all fixed length, then count all lines crossing y=0 and color them green else color them blue.
I have come up with the code below but it doesn't work well in the if statement.
Can someone please have at look? Thank you if you can help!
Question:
How do I correct the if statement to display all the lines and count those lines crossing y = 0?
clear
clc
L = 1.5;
a = -5;
b = 5;
GLines = 0:5:5;
m = 0;
for i = 1:20
X1 = rand(1,i)*(b-a)+a;
Y1 = rand(1,i)*(b-a)+a;
Angle = rand(1,i)*360;
X2 = L*cosd(Angle) + X1;
Y2 = L*sind(Angle) + X2;
if X1(i) < L/2* sind(Angle)
m = m + 1;
plot([X1(i); X2(i)],[Y1(i); Y2(i)], '-g');
else
plot([X1(i); X2(i)],[Y1(i); Y2(i)], '-b');
end
for j = 1:length(GLines)
axis square
ylim([-5 5]);
xlim([-5 5]);
y = yline(GLines(j));
end
end
disp(m)
If a line crosses zero, the sign of Y1 and Y2 will be opposite, so you can do the following:
clear; clc
L = 1.5;
a = -5;
b = 5;
GLines = 0:5:5;
m = 0;
figure;
hold all;
for i = 1:20
X1 = rand*(b-a)+a;
Y1 = rand*(b-a)+a;
Angle = rand*360;
X2 = L*cosd(Angle) + X1;
Y2 = L*sind(Angle) + Y1;
if Y1*Y2 < 0 % if line crosses zero
m = m + 1;
c = 'g'; % color = green
else
c = 'b'; % color = blue
end
plot([X1; X2],[Y1; Y2],'color',c);
end
axis equal
disp(m)
which gives the follwing plot
and correctly outputs m = 2.
I'm trying to covert this Matlab code to Scilab, but I have some problems.
N = 101;
L = 4*pi;
x = linspace(0,L,N);
% It has three data set; 1: past, 2: current, 3: future.
u = zeros(N,3);
s = 0.5;
% Gaussian Pulse
y = 2*exp(-(x-L/2).^2);
u(:,1) = y;
u(:,2) = y;
% Plot the initial condition.
handle_line = plot(x,u(:,2),'LineWidth',2);
axis([0,L,-2,2]);
xlabel('x'); ylabel('u');
title('Wave equation');
% Dirichet Boundary conditions
u(1,:) = 0;
u(end,:) = 0;
filename = 'wave.gif';
for ii=1:100
disp(['at ii= ', num2str(ii)]);
u(2:end-1,3) = s*(u(3:end,2)+u(1:end-2,2)) ...
+ 2*(1-s)*u(2:end-1,2) ...
- u(2:end-1,1);
u(:,1) = u(:,2);
u(:,2) = u(:,3);
handle_line.YData = u(:,2);
drawnow;
frame = getframe(gcf);
im = frame2im(frame);
[A,map] = rgb2ind(im,256);
if ii==1
imwrite(A,map,filename,'gif','LoopCount',Inf,'DelayTime',0.05);
else
imwrite(A,map,filename,'gif','WriteMode','append','DelayTime',0.05);
end
end
I get an error for this line:
handle_line = plot(x,u(:,2),'LineWidth',2);
Error states: Wrong number of output arguments
What should i change to fix it?
The line
axis([0,L,-2,2]);
has to be translated in Scilab to
set(gca(),"data_bounds",[0,L,-2,2]);
Try this out:
N = 101;
L = 4*pi;
x = linspace(0,L,N);
% It has three data set; 1: past, 2: current, 3: future.
u = zeros(N,3);
s = 0.5;
% Gaussian Pulse
y = 2*exp(-(x-L/2).^2);
u(:,1) = y;
u(:,2) = y;
% Define a standard plot range for x and y
x_range=[min(x) max(x)];
y_range=[-max(y) max(y)];
% Plot the initial condition.
plot(x,u(:,2),'LineWidth',2);
axis([0,L,-2,2]);
xlabel('x'); ylabel('u');
title('Wave equation');
% Dirichet Boundary conditions
u(1,:) = 0;
u(end,:) = 0;
filename = 'wave.gif';
for ii=1:100
disp(['at ii= ', num2str(ii)]);
u(2:end-1,3) = s*(u(3:end,2)+u(1:end-2,2)) ...
+ 2*(1-s)*u(2:end-1,2) ...
- u(2:end-1,1);
u(:,1) = u(:,2);
u(:,2) = u(:,3);
plot(x,u(:,2),'LineWidth',2);
axis([x_range y_range]);
frame = getframe(gcf);
im = frame2im(frame);
[A,map] = rgb2ind(im,256);
if ii==1
imwrite(A,map,filename,'gif','LoopCount',Inf,'DelayTime',0.05);
else
imwrite(A,map,filename,'gif','WriteMode','append','DelayTime',0.05);
end
end
I removed the output and added axis limit independently.
I want to move a red star marker along the spiral trajectory with an equal distance of 5 units between the red star points on its circumference like in the below image.
vertspacing = 10;
horzspacing = 10;
thetamax = 10*pi;
% Calculation of (x,y) - underlying archimedean spiral.
b = vertspacing/2/pi;
theta = 0:0.01:thetamax;
x = b*theta.*cos(theta)+50;
y = b*theta.*sin(theta)+50;
% Calculation of equidistant (xi,yi) points on spiral.
smax = 0.5*b*thetamax.*thetamax;
s = 0:horzspacing:smax;
thetai = sqrt(2*s/b);
xi = b*thetai.*cos(thetai);
yi = b*thetai.*sin(thetai);
plot(x,y,'b-');
hold on
I want to get a figure that looks like the following:
This is my code for the circle trajectory:
% Initialization steps.
format long g;
format compact;
fontSize = 20;
r1 = 50;
r2 = 35;
r3= 20;
xc = 50;
yc = 50;
% Since arclength = radius * (angle in radians),
% (angle in radians) = arclength / radius = 5 / radius.
deltaAngle1 = 5 / r1;
deltaAngle2 = 5 / r2;
deltaAngle3 = 5 / r3;
theta1 = 0 : deltaAngle1 : (2 * pi);
theta2 = 0 : deltaAngle2 : (2 * pi);
theta3 = 0 : deltaAngle3 : (2 * pi);
x1 = r1*cos(theta1) + xc;
y1 = r1*sin(theta1) + yc;
x2 = r2*cos(theta2) + xc;
y2 = r2*sin(theta2) + yc;
x3 = r3*cos(theta3) + xc;
y3 = r3*sin(theta3) + yc;
plot(x1,y1,'color',[1 0.5 0])
hold on
plot(x2,y2,'color',[1 0.5 0])
hold on
plot(x3,y3,'color',[1 0.5 0])
hold on
% Connecting Line:
plot([70 100], [50 50],'color',[1 0.5 0])
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0, 1, 1]);
drawnow;
axis square;
for i = 1 : length(theta1)
plot(x1(i),y1(i),'r*')
pause(0.1)
end
for i = 1 : length(theta2)
plot(x2(i),y2(i),'r*')
pause(0.1)
end
for i = 1 : length(theta3)
plot(x3(i),y3(i),'r*')
pause(0.1)
end
I can't think of a way to compute distance along a spiral, so I'm approximating it with circles, in hopes that it will still be useful.
My solution relies on the InterX function from FEX, to find the intersection of circles with the spiral. I am providing an animation so it is easier to understand.
The code (tested on R2017a):
function [x,y,xi,yi] = q44916610(doPlot)
%% Input handling:
if nargin < 1 || isempty(doPlot)
doPlot = false;
end
%% Initialization:
origin = [50,50];
vertspacing = 10;
thetamax = 5*(2*pi);
%% Calculation of (x,y) - underlying archimedean spiral.
b = vertspacing/(2*pi);
theta = 0:0.01:thetamax;
x = b*theta.*cos(theta) + origin(1);
y = b*theta.*sin(theta) + origin(2);
%% Calculation of equidistant (xi,yi) points on spiral.
DST = 5; cRes = 360;
numPts = ceil(vertspacing*thetamax); % Preallocation
[xi,yi] = deal(NaN(numPts,1));
if doPlot && isHG2() % Plots are only enabled if the MATLAB version is new enough.
figure(); plot(x,y,'b-'); hold on; axis equal; grid on; grid minor;
hAx = gca; hAx.XLim = [-5 105]; hAx.YLim = [-5 105];
hP = plot(xi,yi,'r*');
else
hP = struct('XData',xi,'YData',yi);
end
hP.XData(1) = origin(1); hP.YData(1) = origin(2);
for ind = 2:numPts
P = InterX([x;y], makeCircle([hP.XData(ind-1),hP.YData(ind-1)],DST/2,cRes));
[~,I] = max(abs(P(1,:)-origin(1)+1i*(P(2,:)-origin(2))));
if doPlot, pause(0.1); end
hP.XData(ind) = P(1,I); hP.YData(ind) = P(2,I);
if doPlot, pause(0.1); delete(hAx.Children(1)); end
end
xi = hP.XData(~isnan(hP.XData)); yi = hP.YData(~isnan(hP.YData));
%% Nested function(s):
function [XY] = makeCircle(cnt, R, nPts)
P = (cnt(1)+1i*cnt(2))+R*exp(linspace(0,1,nPts)*pi*2i);
if doPlot, plot(P,'Color',lines(1)); end
XY = [real(P); imag(P)];
end
end
%% Local function(s):
function tf = isHG2()
try
tf = ~verLessThan('MATLAB', '8.4');
catch
tf = false;
end
end
function P = InterX(L1,varargin)
% DOCUMENTATION REMOVED. For a full version go to:
% https://www.mathworks.com/matlabcentral/fileexchange/22441-curve-intersections
narginchk(1,2);
if nargin == 1
L2 = L1; hF = #lt; %...Avoid the inclusion of common points
else
L2 = varargin{1}; hF = #le;
end
%...Preliminary stuff
x1 = L1(1,:)'; x2 = L2(1,:);
y1 = L1(2,:)'; y2 = L2(2,:);
dx1 = diff(x1); dy1 = diff(y1);
dx2 = diff(x2); dy2 = diff(y2);
%...Determine 'signed distances'
S1 = dx1.*y1(1:end-1) - dy1.*x1(1:end-1);
S2 = dx2.*y2(1:end-1) - dy2.*x2(1:end-1);
C1 = feval(hF,D(bsxfun(#times,dx1,y2)-bsxfun(#times,dy1,x2),S1),0);
C2 = feval(hF,D((bsxfun(#times,y1,dx2)-bsxfun(#times,x1,dy2))',S2'),0)';
%...Obtain the segments where an intersection is expected
[i,j] = find(C1 & C2);
if isempty(i), P = zeros(2,0); return; end
%...Transpose and prepare for output
i=i'; dx2=dx2'; dy2=dy2'; S2 = S2';
L = dy2(j).*dx1(i) - dy1(i).*dx2(j);
i = i(L~=0); j=j(L~=0); L=L(L~=0); %...Avoid divisions by 0
%...Solve system of eqs to get the common points
P = unique([dx2(j).*S1(i) - dx1(i).*S2(j), ...
dy2(j).*S1(i) - dy1(i).*S2(j)]./[L L],'rows')';
function u = D(x,y)
u = bsxfun(#minus,x(:,1:end-1),y).*bsxfun(#minus,x(:,2:end),y);
end
end
Result:
Note that in the animation above, the diameter of the circle (and hence the distance between the red points) is 10 and not 5.
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);
I am using subplot function of MATLAB. Surprisingly the last plot in each subplot set becomes over-sized. Can anybody help me to resolve this issue? I have experimented with the parameters a little, but no luck. I am not able to post the plot figure.
function plotFluxVariabilityByGene(cRxn,KeggID,geneName)
load iJO1366; % Load the model iJO1366
%Find 'Gene' associated reactions from 'model'
reactions = rxnNamesFromKeggID(model,KeggID);
nCheck = 0; % Initialize counter
% Determine initial subplot dimensions
[R C setSize] = subplotSize(numel(reactions));
for n = 1 : numel(reactions)
% Get the name of nth reaction
rxn = reactions{n};
% Define the array for control reaction fluxes
cRxnArray = getCrxnArray(model,cRxn);
% Initialize storage for lower and upper limit-values
L = []; U = []; Avg = [];
% Get the fluxVariability values
for i = 1 : numel(cRxnArray)
modelMod = changeRxnBounds(model,cRxn,cRxnArray(i),'b');
[L(i) U(i)] = fluxVariability(modelMod,100,'max',{rxn});
Avg(i) = (L(i) + U(i))/2;
%fprintf('mthfcFlux = %f; Li = %f; Ui = %f\n',array(i),L(i),U(i));
end
% adjust the subplot number
nCheck = nCheck + 1;
% Determine the range of n to be saved in one file
if nCheck == 1
start = n;
elseif nCheck == setSize;
stop = n;
end
subplot(R,C,nCheck)
plot(cRxnArray,L,'-r','LineWidth',1); hold on;
plot(cRxnArray,L,'^r','MarkerSize',3,'LineWidth',2);
plot(cRxnArray,U,'-.b','LineWidth',1);
plot(cRxnArray,U,'^b','MarkerSize',2,'LineWidth',2);
plot(cRxnArray,Avg,'-','Color',[0.45,0.45,0.45],'LineWidth',2.5);
% Label X and Y axes
%xlabel([cRxn ' Flux']);
%ylabel(['fluxVariability ' char(rxn)]);
xlabel('Flux');
ylabel('fluxVariability');
hold off;
% Adjust X and Y axes limits
%xmn = min(cRxnArray) - ((max(cRxnArray) - min(cRxnArray))*0.05);
%xmx = max(cRxnArray) + ((max(cRxnArray) - min(cRxnArray))*0.05);
%ymn = min([U L]) - ((max([U L]) - min([U L]))*0.05);
%ymx = max([U L]) + ((max([U L]) - min([U L]))*0.05);
%if xmn ~= xmx
% xlim([xmn xmx]);
%end
%if ymn ~= ymx
% ylim([ymn ymx]);
%end
% Print which reactions are done
fprintf('\n......done for %s',char(rxn));
% If 'setSize' subplots are done then save the set in a file
if nCheck == setSize
saveas(gcf,['TEST/' cRxn 'flux-Vs-' geneName '_fluxVariability' num2str(start) '-' num2str(stop) '.fig']);
saveas(gcf,['TEST/' cRxn 'flux-Vs-' geneName '_fluxVariability' num2str(start) '-' num2str(stop) '.eps']); close(gcf);
% Determine initial subplot dimensions
[R C setSize] = subplotSize(numel(reactions)-n);
% Return nCheck to zero;
nCheck = 0;
end
end
% If nCheck is not equal to 16 then there are subplot that is not saved
% inside the for loop. Let's save it here.
if nCheck ~= setSize
stop = n;
saveas(gcf,['TEST/' cRxn 'flux-Vs-' geneName '_fluxVariability' num2str(start) '-' num2str(stop) '.fig']);
saveas(gcf,['TEST/' cRxn 'flux-Vs-' geneName '_fluxVariability' num2str(start) '-' num2str(stop) '.eps']); close(gcf);
end
fprintf('\nAll done\n');
end
%####################################################
%# Other functions ##
%####################################################
function rxnNames = rxnNamesFromKeggID(model,KeggID)
% Find 'Gene' associated reactions from 'model'
associatedRxns = findRxnsFromGenes(model,KeggID);
% Extract the reaction details from the structure to a cell
rxnDetails = eval(sprintf('associatedRxns.%s',KeggID));
% Extract only the reaction names from the cell
rxnNames = rxnDetails(:,1);
end
%####################################################
function cRxnArray = getCrxnArray(model,cRxn)
% Define the solver
changeCobraSolver('glpk');
% Find solution for the model
sol = optimizeCbModel(model);
% Change the objective of the default model to 'cRxn'
tmpModel = changeObjective(model,cRxn);
% Find slution for the changed model. This gives the maximum and
% minimum possible flux through the reaction 'cRxn' when the model is
% still viable
%solMax = optimizeCbModel(tmpModel,'max');
solMin = optimizeCbModel(tmpModel,'min');
% Create an array of 20 euqally spaced flux values between 'solMin' and
% 'sol.x'
%array = linspace(solMin.f,solMax.f,10);
cRxnArray = linspace(solMin.f,sol.x(findRxnIDs(model,cRxn)),20);
end
%####################################################
function [R C setSize] = subplotSize(remainingPlots)
% Sets number of columns and rows to 3 if total subplot >= 9
if remainingPlots > 7
R = 3; C = 3; setSize = 9;
elseif remainingPlots < 7
R = 2; C = 3; setSize = 6;
elseif remainingPlots < 5
R = 2; C = 2; setSize = 4;
elseif remainingPlots < 4
R = 1; C = 3; setSize = 3;
elseif remainingPlots < 3
R = 1; C = 2; setSize = 2;
end
end
%####################################################
My subplot looks like this:
I suspect its because you are calling subplotSize a second time inside your loop. This could be changing your R and C variables.
I would advise to check the R and C variables at the subplot command on each loop.