error function aborted matlab - matlab
Hi i am running a model in simulink from matlab and i am taking this error
Error using run (line 28) Call to MATLAB function aborted: The first
input argument of the "mpc" command must be one of the following: an
LTI object, an IDMODEL object or a structure of models and offsets.
Block Subsystem2/Control plant (#38) While executing: State During
Action
The embedeed block that i take the erro contains the code
function w0u = MPC(p,x,Sb_bus,Sb,vt,q,theta0,ku,xs,u,vf,KvP,KvI,Kp,Ki,Kd,Droop,DroopAvr,v0,wb,r,t0,umaxnow,time,samplingsTime,Rn,Qn,Rw,Qw,ud,uMinMPC,uMaxMPC,udMaxMPC,wmin,wminw,wmax,wmaxw,tFLR,aFLR,genset3connected,debuggingfile,mpcOn,mpcValSaveTime,mpcValFileName,useUMaxNow,wNLstart)
coder.extrinsic('mpc');
w0u = zeros(2,1);
[w0u] = mpc(p,x,Sb_bus,Sb,vt,q,theta0,ku,xs,u,vf,KvP,KvI,Kp,Ki,Kd,Droop,DroopAvr,v0,wb,r,t0,umaxnow,time,samplingsTime,Rn,Qn,Rw,Qw,ud,uMinMPC,uMaxMPC,udMaxMPC,wmin,wminw,wmax,wmaxw,tFLR,aFLR,genset3connected,debuggingfile,mpcOn,mpcValSaveTime,mpcValFileName,useUMaxNow,wNLstart);
end
And the function mpc is
function [w0u] = mpc(p,Sb_bus,Sb,vt,q,x,theta0,ku,xs,u,umaxnow,vf,KvP,KvI,Kp,Ki,Kd,Droop,DroopAvr,v0,wb,r,t0,time,samplingsTime,Rn,Qn,Rw,Qw,ud,uMinMPC,uMaxMPC,udMaxMPC,wmin,wminw,wmax,wmaxw,tFLR,aFLR,genset3connected,debuggingfile,mpcOn,mpcValSaveTime,mpcValFileName,useUMaxNow,wNLstart)
persistent tupdated w0set
eml.extrinsic('saveVariables');
H = [10; 7];
D = [.02;.025];
if (isempty(tupdated))
% Initialize variables
tupdated = time;
w0set = wNLstart;
elseif (time < t0)
% Wait until t0
elseif (mpcOn == 0)
% If turned off, do nothing.
elseif (time >= tupdated + samplingsTime)
% Update w0
Pbus = sum(p.*Sb)/sum(Sb);
Qbus = sum(q.*Sb)/sum(Sb);
pFLR = aFLR*Sb(end)/Sb_bus*Pbus;
X = [Pbus;Qbus;x];
u0 = u;
udw = ud(1);
%% Calculate the state space equations
[A B B0 Cu Du ~, ud] = makeLinearSystem(H,D,p,Sb_bus,Sb,q,X,vf,vt,theta0,ku,xs,u0,wb,r,KvP,KvI,Kp,Ki,Kd,Droop,DroopAvr,w0set,v0,samplingsTime,ud);
[Aw Bw B0w Cuw Duw ~, udw] = makeLinearWorstCaseSystem(H,D,p,Sb_bus,Sb,q,X,vf,vt,theta0,ku,xs,u0,wb,r,KvP,KvI,Kp,Ki,Kd,Droop,DroopAvr,w0set,v0,samplingsTime,genset3connected,pFLR,udw);
%% Discretize
if(genset3connected)
% Discretize system for normal case
[Ad Bd B0d] = makediscrete(A,B,B0,samplingsTime);
% Discretize system after FLR reacts
[AdFLRp, ~, ~] = makediscrete(Aw,Bw,B0w,samplingsTime-tFLR);
else
% Sets Ad, Bd, B0d and AdFLRp to remove compilation error (matrices
% must have the same size for all cases)
Ad = A;
Bd = B;
B0d = B0;
AdFLRp = Aw;
end
% Discretize system for failure case
[Adw Bdw B0dw] = makediscrete(Aw,Bw,B0w,samplingsTime);
%% Find input optimal
[dw0opt PHI PSI dw] = findInput(X,Ad,Bd,B0d,Cu,Du,Adw,Bdw,B0dw,Cuw,Duw,AdFLRp,pFLR,Rn,Qn,Rw,Qw,ud,udw,u,umaxnow,uMinMPC,uMaxMPC,udMaxMPC,wmin,wmax,wminw,wmaxw,p,Sb,genset3connected,time,debuggingfile,useUMaxNow);
%% Save internal values for plotting
if(mpcValSaveTime >= time && mpcValSaveTime< time + samplingsTime)
saveVariables(mpcValFileName,PHI,PSI,dw)
end
w0set = w0set + dw0opt;
tupdated = time;
end
w0u =w0set;
end
what i have to do?
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..)
Finding Percent Error of a Fourier Series
Find the error as a function of n, where the error is defined as the difference between two the voltage from the Fourier series (vF (t)) and the value from the ideal function (v(t)), normalized to the maximum magnitude (Vm ): I am given this prompt where Vm = 1 V. Below this line is the code which I have written. I am trying to write a function to solve this question: Plot the error versus time for n=3,n=5,n=10, and n=50. (10points). What does it look like I am doing incorrectly? clc; close all; clear all; % define the signal parameters Vm = 1; T = 1; w0 = 2*pi/T; % define the symbolic variables syms n t; % define the signal v1 = Vm*sin(4*pi*t/T); v2 = 2*Vm*sin(4*pi*t/T); % evaluate the fourier series integral an1 = 2/T*int(v1*cos(n*w0*t),0,T/2) + 2/T*int(v2*cos(n*w0*t),T/2,T); bn1 = 2/T*int(v1*sin(n*w0*t),0,T/2) + 2/T*int(v2*sin(n*w0*t),T/2,T); a0 = 1/T*int(v1,0,T/2) + 1/T*int(v2,T/2,T); % obtain C by substituting n in c[n] nmax = 100; n = 1:nmax; a = subs(an1); b = subs(bn1); % define the time vector ts = 1e-2; % ts is sampling the t = 0:ts:3*T-ts; % directly plot the signal x(t) t1 = 0:ts:T-ts; v1 = Vm*sin(4*pi*t1/T).*(t1<=T/2); v2 = 2*Vm*sin(4*pi*t1/T).*(t1>T/2).*(t1<T); v = v1+v2; x = repmat(v,1,3); % Now fourier series reconstruction N = [3]; for p = 1:length(N) for i = 1:length(t) for k = N(p) x(k,i) = a(k)*cos(k*w0*t(i)) + b(k)*sin(k*w0*t(i)); end % y(k,i) = a0+sum(x(:,i)); % Add DC term end end z = a0 + sum(x); figure(1); plot(t,z); %Percent error function [per_error] = percent_error(measured, actual) per_error = abs(( (measured - actual) ./ 1) * 100); end
The purpose of the forum is helping with specific technical questions, not doing your homework.
MATLAB to Scilab conversion: mfile2sci error "File contains no instruction"
I am very new to Scilab, but so far have not been able to find an answer (either here or via google) to my question. I'm sure it's a simple solution, but I'm at a loss. I have a lot of MATLAB scripts I wrote in grad school, but now that I'm out of school, I no longer have access to MATLAB (and can't justify the cost). Scilab looked like the best open alternative. I'm trying to convert my .m files to Scilab compatible versions using mfile2sci, but when running the mfile2sci GUI, I get the error/message shown below. Attached is the original code from the M-file, in case it's relevant. I Searched Stack Overflow and companion sites, Google, Scilab documentation. The M-file code follows (it's a super basic MATLAB script as part of an old homework question -- I chose it as it's the shortest, most straightforward M-file I had): Mmax = 15; N = 20; T = 2000; %define upper limit for sparsity of signal smax = 15; mNE = zeros(smax,Mmax); mESR= zeros(smax,Mmax); for M = 1:Mmax aNormErr = zeros(smax,1); aSz = zeros(smax,1); ESR = zeros(smax,1); for s=1:smax % for-loop to loop script smax times normErr = zeros(1,T); vESR = zeros(1,T); sz = zeros(1,T); for t=1:T %for-loop to carry out 2000 trials per s-value esr = 0; A = randn(M,N); % generate random MxN matrix [M,N] = size(A); An = zeros(M,N); % initialize normalized matrix for h = 1:size(A,2) % normalize columns of matrix A V = A(:,h)/norm(A(:,h)); An(:,h) = V; end A = An; % replace A with its column-normalized counterpart c = randperm(N,s); % create random support vector with s entries x = zeros(N,1); % initialize vector x for i = 1:size(c,2) val = (10-1)*rand + 1;% generate interval [1,10] neg = mod(randi(10),2); % include [-10,-1] if neg~=0 val = -1*val; end x(c(i)) = val; %replace c(i)th value of x with the nonzero value end y = A*x; % generate measurement vector (y) R = y; S = []; % initialize array to store selected columns of A indx = []; % vector to store indices of selected columns coeff = zeros(1,s); % vector to store coefficients of approx. stop = 10; % init. stop condition in = 0; % index variable esr = 0; xhat = zeros(N,1); % intialize estimated x signal while (stop>0.5 && size(S,2)<smax) %MAX = abs(A(:,1)'*R); maxV = zeros(1,N); for i = 1:size(A,2) maxV(i) = abs(A(:,i)'*R); end in = find(maxV == max(maxV)); indx = [indx in]; S = [S A(:,in)]; coeff = [coeff R'*S(:,size(S,2))]; % update coefficient vector for w=1:size(S,2) r = y - ((R'*S(:,w))*S(:,w)); % update residuals if norm(r)<norm(R) index = w; end R = r; stop = norm(R); % update stop condition end for j=1:size(S,2) % place coefficients into xhat at correct indices xhat(indx(j))=coeff(j); end nE = norm(x-xhat)/norm(x); % calculate normalized error for this estimate %esr = 0; indx = sort(indx); c = sort(c); if isequal(indx,c) esr = esr+1; end end vESR(t) = esr; sz(t) = size(S,2); normErr(t) = nE; end %avsz = sum(sz)/T; aSz(s) = sum(sz)/T; %aESR = sum(vESR)/T; ESR(s) = sum(vESR)/T; %avnormErr = sum(normErr)/T; % produce average normalized error for these run aNormErr(s) = sum(normErr)/T; % add new avnormErr to vector of all av norm errors end % just put this here to view the vector mNE(:,M) = aNormErr; mESR(:,M) = ESR; % had an 'end' placed here, might've been unmatched mNE%reshape(mNE,[],Mmax) mESR%reshape(mESR,[],Mmax)] figure dimx = [1 Mmax]; dimy = [1 smax]; imagesc(dimx,dimy,mESR) colormap gray strESR = sprintf('Average ESR, N=%d',N); title(strESR); xlabel('M'); ylabel('s'); strNE = sprintf('Average Normed Error, N=%d',N); figure imagesc(dimx,dimy,mNE) colormap gray title(strNE) xlabel('M'); ylabel('s'); The command used (and results) follow: --> mfile2sci ans = [] ****** Beginning of mfile2sci() session ****** File to convert: C:/Users/User/Downloads/WTF_new.m Result file path: C:/Users/User/DOWNLO~1/ Recursive mode: OFF Only double values used in M-file: NO Verbose mode: 3 Generate formatted code: NO M-file reading... M-file reading: Done Syntax modification... Syntax modification: Done File contains no instruction, no translation made... ****** End of mfile2sci() session ******
To convert the foo.m file one has to enter mfile2sci <path>/foo.m where stands for the path of the directoty where foo.m is. The result is written in /foo.sci
Remove the ```` at the begining of each line, the conversion will proceed normally ?. However, don't expect to obtain a working .sci file as the m2sci converter is (to me) still an experimental tool !
How to optimize new test problem using PlatEMO?
I tried to follow the main tutorial of PlatEMO but I failed to compile it. I tried to modify an already existed function but I've got too many errors. This is the code I already tried: classdef counster < PROBLEM %HELP COUNSTER methods %% Initialization function obj = counster() obj.Global.M = 2; if isempty(obj.Global.D) obj.Global.D = 2; end obj.Global.lower =[0,zeros(1,obj.Global.D-1)-2]; obj.Global.upper = [1,zeros(1,obj.Global.D-1)+2]; obj.Global.encoding = 'real'; end %% Calculate objective values function PopObj = CalObj(obj,X) PopObj(:,1) = X(1); PopObj(:,2) = (1 + X(2))/X(1); end %% Calculate constraint violations function PopCon = CalCon(obj,X) PopCon(:,1)=-9*X(1)-X(2)+6; PopCon(:,2)= -9*X(1)-X(2)+1; end end end and this is an example of built-in function which is correctly working: classdef CF4 < PROBLEM % <problem> <CF> % Constrained benchmark MOP %------------------------------- Reference -------------------------------- % Q. Zhang, A. Zhou, S. Zhao, P. N. Suganthan, W. Liu, and S. Tiwari, % Multiobjective optimization test instances for the CEC 2009 special % session and competition, School of CS & EE, University of Essex, Working % Report CES-487, 2009. %------------------------------- Copyright -------------------------------- % Copyright (c) 2018-2019 BIMK Group. You are free to use the PlatEMO for % research purposes. All publications which use this platform or any code % in the platform should acknowledge the use of "PlatEMO" and reference "Ye % Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform % for evolutionary multi-objective optimization [educational forum], IEEE % Computational Intelligence Magazine, 2017, 12(4): 73-87". %-------------------------------------------------------------------------- methods %% Initialization function obj = CF4() obj.Global.M = 2; if isempty(obj.Global.D) obj.Global.D = 10; end obj.Global.lower = [0,zeros(1,obj.Global.D-1)-2]; obj.Global.upper = [1,zeros(1,obj.Global.D-1)+2]; obj.Global.encoding = 'real'; end %% Calculate objective values function PopObj = CalObj(obj,X) D = size(X,2); J1 = 3 : 2 : D; J2 = 2 : 2 : D; Y = X - sin(6*pi*repmat(X(:,1),1,D)+repmat(1:D,size(X,1),1)*pi/D); h = Y.^2; temp = Y(:,2) < 3/2*(1-sqrt(1/2)); h(temp,2) = abs(Y(temp,2)); h(~temp,2) = 0.125 + (Y(~temp,2)-1).^2; PopObj(:,1) = X(:,1) + sum(h(:,J1),2); PopObj(:,2) = 1-X(:,1) + sum(h(:,J2),2); end %% Calculate constraint violations function PopCon = CalCon(obj,X) t = X(:,2) - sin(6*pi*X(:,1)+2*pi/size(X,2)) - 0.5*X(:,1) + 0.25; PopCon = -t./(1+exp(4*abs(t))); end %% Sample reference points on Pareto front function P = PF(obj,N) P(:,1) = (0:1/(N-1):1)'; P(:,2) = 1 - P(:,1); temp1 = 0.5<P(:,1) & P(:,1)<=0.75; temp2 = 0.75<P(:,1); P(temp1,2) = -0.5*P(temp1,1)+3/4; P(temp2,2) = 1 - P(temp2,1)+0.125; end end end >> main('-algorithm',#MOPSO,'-problem',#counster,'-N',200,'-M',10); It meant to plot a pareto front of counster problem but I have got this: Index exceeds matrix dimensions. Error in INDIVIDUAL (line 79) obj(i).obj = Objs(i,:); Error in GLOBAL/Initialization (line 151) Population = INDIVIDUAL(obj.problem.Init(N)); Error in MOPSO (line 23) Population = Global.Initialization(); Error in GLOBAL/Start (line 120) obj.algorithm(obj); Error in main (line 62) Global.Start();
cell2mat not supported for C code generation in MATLAB Coder
I am trying to convert a neural network function written in MATLAB to C function by using MATLAB Codel APP. But when I try to convert, I am getting as cell2mat is not supported for code generation arrayfun is not supported for code generation How can I replace these functions? My code is as given below. Input X is a 1x2500 matrix and output is a 1x6 matrix. Full code is aavailable in this link boneGrwNN function Y = boneGrwNN(X) x1_step1.ymin = -1; % ===== SIMULATION ======== % Format Input Arguments isCellX = iscell(X); if ~isCellX, X = {X}; end; % Dimensions TS = size(X,2); % timesteps if ~isempty(X) Q = size(X{1},1); % samples/series else Q = 0; end % Allocate Outputs Y = cell(1,TS); % Time loop for ts=1:TS % Input 1 X{1,ts} = X{1,ts}'; Xp1 = mapminmax_apply(X{1,ts},x1_step1); % Layer 1 a1 = tansig_apply(repmat(b1,1,Q) + IW1_1*Xp1); % Layer 2 a2 = softmax_apply(repmat(b2,1,Q) + LW2_1*a1); % Output 1 Y{1,ts} = a2; Y{1,ts} = Y{1,ts}'; end % Format Output Arguments if ~isCellX, Y = cell2mat(Y); end end % ===== MODULE FUNCTIONS ======== % Map Minimum and Maximum Input Processing Function function y = mapminmax_apply(x,settings) y = bsxfun(#minus,x,settings.xoffset); y = bsxfun(#times,y,settings.gain); y = bsxfun(#plus,y,settings.ymin); end % Competitive Soft Transfer Function function a = softmax_apply(n,~) if isa(n,'gpuArray') a = iSoftmaxApplyGPU(n); else a = iSoftmaxApplyCPU(n); end end function a = iSoftmaxApplyCPU(n) nmax = max(n,[],1); n = bsxfun(#minus,n,nmax); numerator = exp(n); denominator = sum(numerator,1); denominator(denominator == 0) = 1; a = bsxfun(#rdivide,numerator,denominator); end function a = iSoftmaxApplyGPU(n) nmax = max(n,[],1); numerator = arrayfun(#iSoftmaxApplyGPUHelper1,n,nmax); denominator = sum(numerator,1); a = arrayfun(#iSoftmaxApplyGPUHelper2,numerator,denominator); end function numerator = iSoftmaxApplyGPUHelper1(n,nmax) numerator = exp(n - nmax); end function a = iSoftmaxApplyGPUHelper2(numerator,denominator) if (denominator == 0) a = numerator; else a = numerator ./ denominator; end end % Sigmoid Symmetric Transfer Function function a = tansig_apply(n,~) a = 2 ./ (1 + exp(-2*n)) - 1; end How can I generate C code for this function ?
You can generate standalone C code only from functions supported by code generation. If you really need C code because your environment doesn't support Matlab, then you have to manually convert unsupported functions or use coder.ceval in order to use external C code that implements the same functions. In your example, you could replace arrayfun calls with traditional for-loops. In order to implement your own cell2mat code, just type open cell2mat so see the source code of the function and try to replicate its logics within your code.