Error only triggers when I don't use parfor? - matlab

In the first Matlab script below when I run it as shown I get no errors what so ever and the code produces the expected results, however when I take out matlabpool open and matlabpool close as well as changing the parfor loop to a for loop, I get the following error:
Running... ??? Error using ==> mldivide
Matrix is singular to working precision.
Error in ==> NSS_betas at 11
betas = G\data.y2.';
Error in ==> DElambda at 19
betas(:,ii) = NSS_betas(P1(:,ii),data); end
Error in ==> Individual_Lambdas at 46
beta{ii} = DElambda(de,dataList, #OF_NSS);
I will happily send CRM_22_12.mat if required.
Why does the error only trigger when I use a regular for loop instead if a parfor loop?
clear all, clc
load Euro_CRM_22_12.mat
matlabpool open
tic
warnState(1) = warning('error', 'MATLAB:singularMatrix');
warnState(2) = warning('error', 'MATLAB:illConditionedMatrix');
mats = 1:50;
mats2 = [2 5 10 30];
% RO: unloop these
de = struct(...
'min', [0;0],...
'max', [50;50],...
'd' , 2,...
'nP' , 500,...
'nG' , 600,...
'ww' , 0.1,...
'F' , 0.5,...
'CR' , 0.99,...
'R' , 0,...
'oneElementfromPm',1);
% RO: initialize beta
beta = cell(size(rates,1),1);
clc, fprintf('Running... ');
%for ii = 1:size(rates,1)
parfor ii = 1:size(rates,1)
% RO: use status indicator for things that take this long
%fprintf('\b\b\b\b\b\b\b%6.2f%%', ii/size(rates,1)*100);
dataList = struct(...
'yM' , rates(ii,:),...
'mats' , mats,...
'model', #NSS,...
'mats2', mats2,...
'y2' , rates(ii,mats2));
beta{ii} = DElambda(de,dataList, #OF_NSS);
end
toc
matlabpool close
%
function [output] = DElambda(de,data,OF)
% RO: also saves time
% warning off; %#ok
warning on verbose;
P1 = zeros(de.d,de.nP);
Pu = zeros(de.d,de.nP);
for ii = 1:de.d
P1(ii,:) = de.min(ii,1)+(de.max(ii,1)-de.min(ii,1))*rand(de.nP,1); end
P1(:,1:de.d) = diag(de.max);
P1(:,de.d+1:2*de.d) = diag(de.min);
% RO: pre allocate betas
betas = zeros(size(data.y2,2), de.nP);
for ii = 1:de.nP
betas(:,ii) = NSS_betas(P1(:,ii),data); end
Params = vertcat(betas,P1);
Fbv = NaN(de.nG,1);
% must pass OF as #OF
F = zeros(de.nP,1);
P = zeros(de.nP,1);
for ii = 1:de.nP
F(ii) = OF(Params(:,ii)',data);
P(ii) = pen(P1(:,ii),de,F(ii));
F(ii) = F(ii)+P(ii);
end
[Fbest indice] = min(F);
xbest = Params(:,indice);
Col = 1:de.nP;
% RO: pre allocate betasPu
betasPu = zeros(size(data.y2,2), de.nP);
% RO: if Fbest hasn't changed for 25 generations,
% it's not gonna anymore: break off
count = 0;
for g = 1:de.nG
P0 = P1;
rowS = randperm(de.nP).';
colS = randperm(4).';
% RO: replace circshift for JIT accelleration
% RS = circshift(rowS,colS(1));
% R1 = circshift(rowS,colS(2));
% R2 = circshift(rowS,colS(3));
% R3 = circshift(rowS,colS(4));
RS = rowS([end-colS(1)+1:end 1:end-colS(1)]);
R1 = rowS([end-colS(2)+1:end 1:end-colS(2)]);
R2 = rowS([end-colS(3)+1:end 1:end-colS(3)]);
R3 = rowS([end-colS(4)+1:end 1:end-colS(4)]);
% mutate
Pm = P0(:,R1) + de.F*(P0(:,R2)-P0(:,R3));
if de.R>0, Pm = Pm+de.r*randn(de.d,de.nP); end
% crossover
PmElements = rand(de.d,de.nP)<de.CR;
if de.oneElementfromPm
% RO: JIT...
%Row = unidrnd(de.d,1,de.nP);
Row = ceil(de.d .* rand(1,de.nP));
ExtraPmElements = sparse(Row,Col,1,de.d,de.nP);
PmElements = PmElements|ExtraPmElements;
end
P0_Elements = ~PmElements;
Pu(:,RS) = P0(:,RS).*P0_Elements+PmElements.*Pm;
% RO: inline NSS_betas, so that this loop can
% be compiled by the JIT
mats = data.mats2.';
yM = data.y2.';
nObs = size(data.y2,2);
one = ones(nObs,1);
% RO: version below is faster
% for ii = 1:de.nP
% %betasPu(:,ii) = NSS_betas(Pu(:,ii),data);
%
% lambda = Pu(:,ii);
% G = [one,...
% (1-exp(-mats/lambda(1)))./(mats/lambda(1)),...
% ((1-exp(-mats/lambda(1)))./(mats/lambda(1)) - exp(-mats/lambda(1))),...
% ((1-exp(-mats/lambda(2)))./(mats/lambda(2)) - exp(-mats/lambda(2)))];
%
% betasPu(:,ii) = G\yM;
%
% end
aux = bsxfun(#rdivide, mats, Pu(:).');
aux2 = exp(-aux);
aux3 = (1-aux2)./aux;
for ii = 1:2:2*de.nP
% betasPu(:,(ii+1)/2) =[...
% one,...
% aux3(:,ii),...
% aux3(:,ii) - aux2(:,ii),...
% aux3(:,ii+1) - aux2(:,ii+1)] \ yM;
G=[one, aux3(:,ii), aux3(:,ii) - aux2(:,ii),aux3(:,ii+1) - aux2(:,ii+1)];
try
betasPu(:,(ii+1)/2) =G\yM;
catch ME
CondPen(1,(ii+1)/2)=0;
end
end
ParamsPu = [betasPu;Pu];
flag = 0;
mats = data.mats;
yM = data.yM;
for ii = 1:de.nP
% RO: inline OF_NSS.m here for JIT accelleration
%Ftemp = OF(ParamsPu(:,ii).',data);
beta = ParamsPu(:,ii).';
%model = data.model;
yy = zeros(size(yM));
for jj = 1:size(beta,3)
% RO: inline for JIT accelleration
%y(ii,:) = model(beta(:,:,ii),mats);
betai = beta(:,:,jj);
gam1 = mats/betai(5);
gam2 = mats/betai(6);
aux1 = 1-exp(-gam1);
aux2 = 1-exp(-gam2);
% I have a feeling this is the same as G and therefore
% this can be done shorter and quicker...
% something like yy(jj,:) = sum(G,2)
yy(jj,:) = ...
betai(1) + ...
betai(2)*(aux1./gam1) + ...
betai(3)*(aux1./gam1+aux1-1) + ...
betai(4)*(aux2./gam2+aux2-1);
end
yy = yy-yM;
% RO: this whole loop can be replaced...
% ObjVal = 0;
% for i = 1:size(yM,1) %dim
% ObjVal = ObjVal+dot(aux(i,:)',aux(i,:)');
% %ObjVal = sum(ObjVal);
% end
% ObjVal
% RO ...by this one-liner
Ftemp = sum(yy(:).^2);
% RO: inline penalty here as well
Ptemp = 0;%pen(Pu(:,ii),de,F(ii));
Ftemp = Ftemp+Ptemp;%+CondPen(1,ii);
if Ftemp <= F(ii);
P1(:,ii) = Pu(:,ii);
F(ii) = Ftemp;
if Ftemp < Fbest
Fbest = Ftemp; xbest = ParamsPu(:,ii);
flag = 1;
count = 0;
end
else
P1(:,ii) = P0(:,ii);
end
end
if flag
Fbv(g) = Fbest; end
% RO: if Fbest hasn't changed for 25 generatios, break off
count = count + 1;
if count > 25, break; end
end
output.Fbest = Fbest;
output.xbest = xbest;
output.Fbv = Fbv;
end
% look to inline penalty later (i.e. incoporate into code
function penVal = pen(~,~,~)%pen(beta,pso,vF,data)
penVal = 0;
end
%
function [betas r r2] = NSS_betas(lambda,data)
mats = data.mats2.';
nObs = size(data.y2,2);
G = [ones(nObs,1),...
(1-exp(-mats/lambda(1)))./(mats/lambda(1)),...
((1-exp(-mats/lambda(1)))./(mats/lambda(1)) - exp(-mats/lambda(1))),...
((1-exp(-mats/lambda(2)))./(mats/lambda(2)) - exp(-mats/lambda(2)))];
betas = G\data.y2.';
% RO: output hardly ever needed, while rank()
% is very time consuming
if nargout > 1 && ~isnan(G)
r = rank(G);
r2 = rcond(G);
end
end

It's a bit cryptic, but here's what I can tell you for sure.
Error in ==> NSS_betas at 11
betas = G\data.y2.';
Error in ==> DElambda at 19
betas(:,ii) = NSS_betas(P1(:,ii),data); end
Error in ==> Individual_Lambdas at 46
beta{ii} = DElambda(de,dataList, #OF_NSS);
Essentially, this means that the G matrix is singular, and thus doesn't have a solution. That would be this:
G = [ones(nObs,1),...
(1-exp(-mats/lambda(1)))./(mats/lambda(1)),...
((1-exp(-mats/lambda(1)))./(mats/lambda(1)) - exp(-mats/lambda(1))),...
((1-exp(-mats/lambda(2)))./(mats/lambda(2)) - exp(-mats/lambda(2)))];
betas = G\data.y2.';
What I would do to further diagnose this is to set the stop on error flag. There is a few ways to do this, one from the gui, and another via command. Take a look to see if the matrix looks correct. Odds are, something isn't right. Trace back the error, and you'll figure it out.

Related

Fast approach in matlab to estimate linear regression with AR terms

I am trying to estimate regression and AR parameters for (loads of) linear regressions with AR error terms. (You could also think of this as a MA process with exogenous variables):
, where
, with lags of length p
I am following the official matlab recommendations and use regArima to set up a number of regressions and extract regression and AR parameters (see reproducible example below).
The problem: regArima is slow! For 5 regressions, matlab needs 14.24sec. And I intend to run a large number of different regression models. Is there any quicker method around?
y = rand(100,1);
r2 = rand(100,1);
r3 = rand(100,1);
r4 = rand(100,1);
r5 = rand(100,1);
exo = [r2 r3 r4 r5];
tic
for p = 0:4
Mdl = regARIMA(3,0,0);
[EstMdl, ~, LogL] = estimate(Mdl,y,'X',exo,'Display','off');
end
toc
Unlike the regArima function which uses Maximum Likelihood, the Cochrane-Orcutt prodecure relies on an iteration of OLS regression. There are a few more particularities when this approach is valid (refer to the link posted). But for the aim of this question, the appraoch is valid, and fast!
I modified James Le Sage's code which covers only AR lags of order 1, to cover lags of order p.
function result = olsc(y,x,arterms)
% PURPOSE: computes Cochrane-Orcutt ols Regression for AR1 errors
%---------------------------------------------------
% USAGE: results = olsc(y,x)
% where: y = dependent variable vector (nobs x 1)
% x = independent variables matrix (nobs x nvar)
%---------------------------------------------------
% RETURNS: a structure
% results.meth = 'olsc'
% results.beta = bhat estimates
% results.rho = rho estimate
% results.tstat = t-stats
% results.trho = t-statistic for rho estimate
% results.yhat = yhat
% results.resid = residuals
% results.sige = e'*e/(n-k)
% results.rsqr = rsquared
% results.rbar = rbar-squared
% results.iter = niter x 3 matrix of [rho converg iteration#]
% results.nobs = nobs
% results.nvar = nvars
% results.y = y data vector
% --------------------------------------------------
% SEE ALSO: prt_reg(results), plt_reg(results)
%---------------------------------------------------
% written by:
% James P. LeSage, Dept of Economics
% University of Toledo
% 2801 W. Bancroft St,
% Toledo, OH 43606
% jpl#jpl.econ.utoledo.edu
% do error checking on inputs
if (nargin ~= 3); error('Wrong # of arguments to olsc'); end;
[nobs nvar] = size(x);
[nobs2 junk] = size(y);
if (nobs ~= nobs2); error('x and y must have same # obs in olsc'); end;
% ----- setup parameters
ITERMAX = 100;
converg = 1.0;
rho = zeros(arterms,1);
iter = 1;
% xtmp = lag(x,1);
% ytmp = lag(y,1);
% truncate 1st observation to feed the lag
% xlag = x(1:nobs-1,:);
% ylag = y(1:nobs-1,1);
yt = y(1+arterms:nobs,1);
xt = x(1+arterms:nobs,:);
xlag = zeros(nobs-arterms,arterms);
for tt = 1 : arterms
xlag(:,nvar*(tt-1)+1:nvar*(tt-1)+nvar) = x(arterms-tt+1:nobs-tt,:);
end
ylag = zeros(nobs-arterms,arterms);
for tt = 1 : arterms
ylag(:,tt) = y(arterms-tt+1:nobs-tt,:);
end
% setup storage for iteration results
iterout = zeros(ITERMAX,3);
while (converg > 0.0001) & (iter < ITERMAX),
% step 1, using intial rho = 0, do OLS to get bhat
ystar = yt - ylag*rho;
xstar = zeros(nobs-arterms,nvar);
for ii = 1 : nvar
tmp = zeros(1,arterms);
for tt = 1:arterms
tmp(1,tt)=ii+nvar*(tt-1);
end
xstar(:,ii) = xt(:,ii) - xlag(:,tmp)*rho;
end
beta = (xstar'*xstar)\xstar' * ystar;
e = y - x*beta;
% truncate 1st observation to account for the lag
et = e(1+arterms:nobs,1);
elagt = zeros(nobs-arterms,arterms);
for tt = 1 : arterms
elagt(:,tt) = e(arterms-tt+1:nobs-tt,:);
end
% step 2, update estimate of rho using residuals
% from step 1
res_rho = (elagt'*elagt)\elagt' * et;
rho_last = rho;
rho = res_rho;
converg = sum(abs(rho - rho_last));
% iterout(iter,1) = rho;
iterout(iter,2) = converg;
iterout(iter,3) = iter;
iter = iter + 1;
end; % end of while loop
if iter == ITERMAX
% error('ols_corc did not converge in 100 iterations');
print('ols_corc did not converge in 100 iterations');
end;
result.iter= iterout(1:iter-1,:);
% after convergence produce a final set of estimates using rho-value
ystar = yt - ylag*rho;
xstar = zeros(nobs-arterms,nvar);
for ii = 1 : nvar
tmp = zeros(1,arterms);
for tt = 1:arterms
tmp(1,tt)=ii+nvar*(tt-1);
end
xstar(:,ii) = xt(:,ii) - xlag(:,tmp)*rho;
end
result.beta = (xstar'*xstar)\xstar' * ystar;
e = y - x*result.beta;
et = e(1+arterms:nobs,1);
elagt = zeros(nobs-arterms,arterms);
for tt = 1 : arterms
elagt(:,tt) = e(arterms-tt+1:nobs-tt,:);
end
u = et - elagt*rho;
result.vare = std(u)^2;
result.meth = 'olsc';
result.rho = rho;
result.iter = iterout(1:iter-1,:);
% % compute t-statistic for rho
% varrho = (1-rho*rho)/(nobs-2);
% result.trho = rho/sqrt(varrho);
(I did not adapt in the last 2 lines the t-test for rho vectors of length p, but this should be straight forward to do..)

Matlab: ode15i solver raises error about dimensions, I fail to see where

CODE
% Why?
tstart = 0;
tfinal = 1;
tspan = [tstart tfinal];
options = odeset('Events',#myEventsFcn);
% Initial conditions
y0 = [0,-0.6,0,0,0,0];
yp0 = [0,0,0,0,0,0];
% decic funtion calculates consistent ICs
[y0,yp0] = decic(#StateI,t0,y0,[0 1 0 0 0 0],yp0,[0 0 0 0 0 0]);
% Arrays for plots
tout = tstart;
sout = y0(1:1);
bout = y0(2:2);
zout = y0(3:3);
svout = y0(4:4);
bvout = y0(5:5);
zvout = y0(6:6);
% ode15i solves system of implicit ODEs
[t,y,te,ye,ie] = ode15i(#StateI,tspan,y0,yp0,options);
% system of implicit ODEs defined as StateI function
function res = StateI(t,y,yp)
% Constants
mS = 3*10^(-4); % [kg]
JS = 5*10^(-9); % [kgm]
mB = 4.5*10^(-3); % [kg]
g = 9.81; % [m/s^2]
JB = 7*10^(-7); % [kgm]
lS = 10^(-2); % [m]
lG = 1.5*10^(-2); % [m]
cp = 5.6*10^(-3); % [N/rad]
res = [(mS+mB)*yp(6) + mB*lS*yp(4) + mB*lG*yp(5) + (mS+mB)*g;
mB*lS*yp(6) + (JS+mB*lS^2)*yp(4) + mB*lS*lG*yp(5) - cp*(y(2)-y(1)) + mB*lS*g;
mB*lG*yp(6) + mB*lS*lG*yp(4) + (JB+mB*lG^2)*yp(5) - cp*(y(1)-y(2)) + mB*lG*g;
y(4)-yp(1);
y(5)-yp(2);
y(6)-yp(3)];
end
% my events defined in myEventsFcn
function [value,isterminal,direction] = myEventsFcn(t,y,yp)
% Constants
mS = 3*10^(-4); % [kg]
mB = 4.5*10^(-3); % [kg]
g = 9.81; % [m/s^2]
rS = 3.1*10^(-3); % [m]
lS = 10^(-2); % [m]
r0 = 2.5*10^(-3); % [m]
hS = 2*10^(-2); % [m]
lG = 1.5*10^(-2); % [m]
lB = 2.01*10^(-2); % [m]
hB = 2*10^(-2); % [m]
cp = 5.6*10^(-3); % [N/rad]
Z2 = -(mS+mB)*g-mB*lG*yp(5);
Z1II = (cp*(y(2)+(rS-r0)/hS)-rS*Z2-mB*lS*lG*yp(5)-mB*lS*g)/hS;
value = [y(1)+(rS-r0)/hS, y(1)-(rS-r0)/hS, Z1II, y(2)-(lS+lG-lB- r0)/hB];
isterminal = [1, 1, 1, 1];
direction = [-1, 1, -1, 1];
end
ERROR MESSAGE
Matrix dimensions must agree.
Error in odezero (line 46)
indzc = find((sign(vL) ~= sign(vR)) & (direction .* (vR - vL) >= 0));
Error in ode15i (line 506)
[te,ye,ie,valt,stop] = odezero(#ntrp15i,#events_aux,events_args,valt,...
Error in silly (line 24)
[t,y,te,ye,ie] = ode15i(#StateI,tspan,y0,yp0,options);
So I ran this code before, no problem, then this error started popping up. I cannot see where this error might occur. I tried transposing my vectors y0 and yp0, which is not sucessful, but it does give another error message, which seems strange because I think Matlab's ode solvers can handle transposed initial conditions.
Best regards
You code runs just fine on my version of MATLAB (2018b). Check your version.

MATLAB: Not Enough Input Arguements

I've attempted to run this code multiple times and have had zero luck since I added in the last for loop. Before the error, the vector k wouldn't update so the vector L was the same number repeated.
I can't figure out why I am getting the 'Not enough input arguments' error when it was working fine beforehand.
Any help would be much appreciated!
% Set up parameters of the functions
omega = 2*pi/10; % 1/s
g = 9.81; % m/s^2
h = 20; % m
parms = [omega, g, h];
% Set up the root finding variables
etol = 1e-6; % convergence criteria
iter = 100; % maximum number of iterations
f = #my_fun; % function pointer to my_func
fp = #my_fprime; % function pointer to my_fprime
k0 = kguess(parms); % initial guess for root
% Find the root
[k, error, n_iterations] = newtraph(f, fp, k0, etol, iter, parms);
% Get the wavelength
if n_iterations < iter
% Converged correctly
L = 2 * pi / k;
else
% Did not converge
disp('ERROR: Maximum number of iterations exceeded')
return
end
wave = load('wavedata.dat');
dt = 0.04; %s
%dh = 0.234; %water depth in meters
wave = wave*.01; %covnverts from meters to cm
nw = wave([926:25501],1);
a = length(nw);
t = 0;
spot = 1;
points = zeros(1,100);
for i = 1:a-1
t=t+dt;
if nw(i) < 0
if nw(i+1) > 0
points(spot)=t;
spot=spot+1;
t=0;
end
end
end
omega = 2*pi./points; %w
l = length(points);
L = zeros(1,509);
k = zeros(1,509);
for j = 1:l
g = 9.81; % m/s^2
h = 0.234; % m
parms = [omega(j), g, h];
% Set up the root finding variables
etol = 1e-6; % convergence criteria
iter = 100; % maximum number of iterations
f = #my_fun; % function pointer to my_func
fp = #my_fprime; % function pointer to my_fprime
k0(j) = kguess(parms); % initial guess for root
% Find the root
[k(j), error, n_iterations] = newtraph(f, fp, k0(j), etol, iter, parms);
% Get the wavelength
if n_iterations < iter
% Converged correctly
L(j) = 2 * pi / k(j);
else
% Did not converge
disp('ERROR: Maximum number of iterations exceeded')
return
end
end
function [ f ] = my_fun(k,parms)
%MY_FUN creates a function handle for linear dispersion
% Detailed explanation goes here
w = parms(1) ;
g = parms(2);
h = parms(3);
f = g*k*tanh(k*h)-(w^2);
end
function [ fp ] = my_fprime(k,parms)
%MY_FPRIME creates a function handle for first derivative of linear
% dispersion.
g = parms(2);
h = parms(3);
% w = 2*pi/10; % 1/s
% g = 9.81; % m/s^2
% h = 20; % m
fp = g*(k*h*((sech(k*h)).^2) + tanh(k*h));
end
function [ k, error, n_iterations ] = newtraph( f, fp, k0, etol, iterA, parms )
%NEWTRAPH Estimates the value of k using the newton raphson method.
if nargin<3,error('at least 3 input arguments required'),end
if nargin<4|isempty(etol),es=etol;end
if nargin<5|isempty(iterA),maxit=iterA;end
iter = 0;
k = k0;
%func =#f;
%dfunc =#fp;
while (1)
xrold = k;
k = k - f(k)/fp(k);
iter = iter + 1;
if k ~= 0, ea = abs((k - xrold)/k) * 100; end
if ea <= etol | iter >= iterA, break, end
end
error = ea;
n_iterations = iter;
end
In function newtraph at line 106 (second line in the while(1) loop), you forgot to pass parms to the function call f:
k = k - f(k)/fp(k);
should become
k = k - f(k,parms)/fp(k,parms);

Last plot in subplot becomes over-sized

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.

Matlab Iris Classification input size mistmach

I am very new to Matlab. What i am trying to do is classify the iris dataset using Cross-Validation (that means that i have to split the dataset in 3: trainingSet, validationSet, and test set) . In my mind everything i write here is ok (beeing a beginner is hard sometimes). So i could use a little help...
This is the function that splits the data (first 35(70% of the data) are the training set, the rest is the validation set(15%) and 15% i will use later for the test set)
close all; clear ;
load fisheriris;
for i = 1:35
for j = 1:4
trainSeto(i,j) = meas(i,j);
end
end
for i = 51:85
for j = 1:4
trainVers(i-50,j) = meas(i,j);
end
end
for i = 101:135
for j = 1:4
trainVirg(i-100,j) = meas(i,j);
end
end
for i = 36:43
for j = 1:4
valSeto(i-35,j) = meas(i,j);
end
end
for i = 86:93
for j = 1:4
valVers(i-85,j) = meas(i,j);
end
end
for i = 136:143
for j = 1:4
valVirg(i-135,j) = meas(i,j);
end
end
for i = 44:50
for j = 1:4
testSeto(i-43,j) = meas(i,j);
end
end
for i = 94:100
for j = 1:4
testVers(i-93,j) = meas(i,j);
end
end
for i = 144:150
for j = 1:4
testVirg(i-143,j) = meas(i,j);
end
end
And this is the main script:
close all; clear;
%%the 3 tipes of iris
run divinp
% the representation of the 3 classes(their coding)
a = [-1 -1 +1]';
b = [-1 +1 -1]';
c = [+1 -1 -1]';
%training set
trainInp = [trainSeto trainVers trainVirg];
%the targets
T = [repmat(a,1,length(trainSeto)) repmat(b,1,length(trainVers)) repmat(c,1,length(trainVirg))];
%%the training
trainCor = zeros(10,10);
valCor = zeros(10,10);
Xn = zeros(1,10);
Yn = zeros(1,10);
for k = 1:10,
Yn(1,k) = k;
for n = 1:10,
Xn(1,n) = n;
net = newff(trainInp,T,[k n],{},'trainbfg');
net = init(net);
net.divideParam.trainRatio = 1;
net.divideParam.valRatio = 0;
net.divideParam.testRatio = 0;
net.trainParam.max_fail = 2;
valInp = [valSeto valVers valVirg];
valT = [repmat(a,1,length(valSeto)) repmat(b,1,length(valVers)) repmat(c,1,length(valVirg))];
[net,tr] = train(net,trainInp,T);
Y = sim(net,trainInp);
[Yval,Pfval,Afval,Eval,perfval] = sim(net,valInp,[],[],valT);
% calculate [%] of correct classifications
trainCor(k,n) = 100 * length(find(T.*Y > 0)) / length(T);
valCor(k,n) = 100 * length(find(valT.*Yval > 0)) / length(valT);
end
end
figure
surf(Xn,Yn,trainCor/3);
view(2)
figure
surf(Xn,Yn,valCor/3);
view(2)
I get this error
Error using trainbfg (line 120) Inputs and targets have different
numbers of samples.
Error in network/train (line 106) [net,tr] =
feval(net.trainFcn,net,X,T,Xi,Ai,EW,net.trainParam);
Error in ClassIris (line 38)
[net,tr] = train(net,trainInp,T);
close all; clear ;
load fisheriris;
trainSetoIndx = 1:35;
trainVersIndx = 51:85; % or: trainVersIndx = trainSetoIndx + 50;
trainVirgIndx = 101:135;
colIndx = 1:4;
trainSeto = meas(trainSetoIndx, colIndx);
trainVers = meas(trainVersIndx, colIndx);
trainVirg = meas(trainVirgIndx, colIndx);
valSetoIndx = 36:43;
valVersIndx = 86:93;
valVirgIndx = 136:143
valSeto = meas(valSetoIndx, colIndx);
valVers = meas(valVersIndx, colIndx);
valVirg = meas(valVirgIndx, colIndx);
testSetoIndx = 44:50;
testVersIndx = 94:100;
testVirgIndx = 144:150
testSeto = meas(testSetoIndx, colIndx);
testVers = meas(testVersIndx, colIndx);
testVirg = meas(testVirgIndx, colIndx);
i have writen it with ":" also still the same problem it's something with repmat.. i don't know how to use it properly or newff :D
Just to get you started, you can rewrite your code loops as follows:
trainSetoIndx = 1:35;
trainVersIndx = 51:85; % or: trainVersIndx = trainSetoIndx + 50;
trainVirgIndx = 101:135; % or: trainVirgIndx = trainSetoIndx + 100;
colIndx = 1:4; % can't tell if this is all the columns in meas
trainSeto = meas(trainIndx, colIndx);
trainVers = meas(trainVersIndx, colIndx);
trainVirg = meas(trainVirgIndx, colIndx);
The do the same thing for all the others:
valSetoIndx = 36:43;
etc.
Next, simply type whos at the command prompt and you will see the sizes of all the arrays you have created. See whether the ones that need to be the same size have, in fact, the same dimensions.