Scientific computing / Computacao cientifica
Sparse and advanced solvers / Esparsas e solvers avancados
EN: Stage 5 bounded real sparse matrices, iterative systems, symmetric eigenproblems, nonlinear systems, stiff IVPs and linear programming. PT: Etapa 5 de esparsas reais limitadas, sistemas iterativos, autoproblemas simetricos, sistemas nao lineares, PVI rigidos e programacao linear.
EN: Canonical bounded sparse values
sparse(A) accepts a finite real dense matrix or an existing Sparse value; sparse(m,n) creates zeros; sparse(i,j,v,m,n) accepts equal-length finite real vectors with integer 1-based row/column indices. Duplicate triplets sum in input order after sorting; nonfinite sums error, zeros are eliminated. Dimensions are nonnegative integer Numbers, each <=16777216, and the logical product rows*cols<=16777216 even with zero stored entries. Input triplets AND stored nnz are capped at 1000000: this is not large unbounded sparse storage.
Value::Sparse stores rows, cols and canonical row/column-sorted unique nonzero finite triplets (internal indices zero-based). class(S) is double, issparse(S) is true. full(S) returns a dense real matrix; full also accepts finite real dense matrices. nnz accepts finite real dense/sparse matrices or a finite Number; issparse accepts any value. These four builtins have one output. No logical/complex sparse construction, scalar sparse(A), generalized sparse MATLAB dispatch or automatic conversion of existing dense-only solvers is implied. Studio read-only sparse metadata is upcoming, not a delivered editable sparse grid.
double(S) returns a validated sparse clone preserving representation, not a dense conversion. Only full(S) materializes a dense matrix. This is behavior of the existing double builtin, not a new builtin.
S=sparse([1,1,2],[1,1,2],[3,-3,5],2,2);
disp(issparse(S) && strcmp(class(S),'double') && nnz(S)==1);
disp(all(full(S)==[0,0;0,5]));
stored=S;
disp(issparse(double(stored))&&all(full(double(stored))==full(stored)));
Z=sparse(3,4);
disp(nnz(Z)==0 && all(size(Z)==[3,4]) && !issparse(full(Z)));
disp(nnz([0,2;3,0])==2 && nnz(0)==0);PT: Valores esparsos canonicos e limitados
sparse(A) aceita matriz real densa finita ou Sparse existente; sparse(m,n) cria zeros; sparse(i,j,v,m,n) aceita vetores reais finitos de mesmo comprimento com indices inteiros 1-based. Tripletas duplicadas somam na ordem de entrada apos ordenacao; soma nao finita gera erro e zeros sao eliminados. Dimensoes sao Numbers inteiros nao negativos, cada uma <=16777216, com produto logico rows*cols<=16777216 mesmo sem entradas armazenadas. Tripletas de entrada E nnz armazenado limitados a 1000000: nao e armazenamento esparso grande ilimitado.
Value::Sparse armazena rows, cols e tripletas canonicas ordenadas por linha/coluna, unicas, nao zero e finitas (indices internos zero-based). class(S) e double e issparse(S) e true. full(S) retorna matriz real densa e tambem aceita densas reais finitas. nnz aceita densas/esparsas reais finitas ou Number finito; issparse aceita qualquer valor. Os quatro builtins tem uma saida. Sem construcao esparsa logica/complexa, sparse(A) escalar, dispatch MATLAB geral ou conversao automatica de solvers que exigem densas. Metadados esparsos somente leitura no Studio estao previstos, nao uma grade esparsa editavel entregue.
double(S) retorna clone esparso validado preservando a representacao, nao uma conversao densa. Somente full(S) materializa matriz densa. Este e o comportamento do builtin double existente, nao um novo builtin.
S=sparse([1,2,2],[1,2,2],[4,2,-2],2,2);
disp(issparse(S) && strcmp(class(S),'double') && nnz(S)==1);
disp(all(full(S)==[4,0;0,0]));
stored=S;
disp(issparse(double(stored))&&all(full(double(stored))==full(stored)));
disp(nnz(sparse(0,3))==0 && all(size(sparse(0,3))==[0,3]));EN: PCG and restarted GMRES
pcg(A,b[,tol[,maxiter]]) assumes SPD: it checks exact stored symmetry, not positive definiteness by factorization. gmres(A,b[,restart[,tol[,maxiter]]]) accepts general square real operators. A is finite real dense/sparse, b a matching finite real vector (Number allowed for order one). Both start from zero, without user preconditioners or x0. tol is a positive finite Number, default 1e-6; maxiter is an integer 1..10000, default max(1,min(n,1000)). GMRES restart is an integer 1..min(n,10000), default max(1,min(n,20)), internally capped by maxiter; its basis/Hessenberg/workspace must fit 16777216 elements.
At most four outputs [x,flag,relres,iter]: x is an n-by-1 column; flag=0 converged, 1 exhausted, 2 numerical breakdown. relres is the true norm(b-A*x)/norm(b), with zero for a zero RHS. iter counts completed steps, TOTAL Arnoldi steps including all GMRES restarts, not outer cycles or MATLAB's pair. The best finite true-residual iterate is retained (GMRES checks cycle ends); flags 1/2 return this iterate rather than implying convergence. Output masks including [~,flag,relres,iter] and named handles preserve positions; invalid arguments are still validated when outputs are discarded.
A=[4,1;1,3]; b=[1;2];
[x,flag,relres,iter]=pcg(sparse(A),b);
disp(flag==0 && size(x,2)==1 && all(abs(A*x-b)<1e-6) && relres<1e-6 && iter<=2);
B=[3,1;0,2];
[y,status,rr,steps]=gmres(sparse(B),b,1,1e-8,100);
disp(status==0 && all(abs(B*y-b)<1e-7) && rr<1e-8 && steps>1 && steps<=100);
[~,ok,zero,used]=pcg(A,[0;0]);
disp(ok==0 && zero==0 && used==0);PT: PCG e GMRES reiniciado
pcg(A,b[,tol[,maxiter]]) assume SPD: verifica simetria armazenada exata, sem fatorar para provar definicao positiva. gmres(A,b[,restart[,tol[,maxiter]]]) aceita operador quadrado real geral. A e real finita densa/esparsa, b vetor real finito compativel (Number para ordem um). Inicio em zero, sem precondicionadores ou x0 do usuario. tol Number positivo finito tem padrao 1e-6; maxiter inteiro 1..10000 tem padrao max(1,min(n,1000)). restart do GMRES e inteiro 1..min(n,10000), padrao max(1,min(n,20)), limitado internamente por maxiter; base/Hessenberg/workspace cabem em 16777216 elementos.
Ate quatro saidas [x,flag,relres,iter]: x coluna n por 1; flag=0 convergiu, 1 esgotou, 2 quebra numerica. relres e norm(b-A*x)/norm(b) verdadeiro, zero para RHS zero. iter conta passos completos, TOTAL Arnoldi entre reinicios GMRES, nao ciclos externos nem par MATLAB. Preserva o melhor iterando finito por residuo verdadeiro (GMRES avalia ao fim dos ciclos); flags 1/2 nao significam convergencia. Mascaras como [~,flag,relres,iter] e handles nomeados preservam posicoes; argumentos invalidos continuam validados com saidas descartadas.
A=[4,1;1,3]; b=[1;2];
solver=@pcg;
[x,flag,rr,steps]=solver(sparse(A),b,1e-8,20);
disp(flag==0 && size(x,2)==1 && all(abs(A*x-b)<1e-7) && rr<1e-8 && steps<=20);
[~,flag,rr,steps]=gmres(A,[0;0]);
disp(flag==0 && rr==0 && steps==0);EN: Real symmetric bounded eigs
eigs(A[,k[,which]]) accepts finite real symmetric dense/sparse square matrices with EXACT symmetry only. It materializes a bounded DENSE symmetric reduction using faer self-adjoint EVD, order <=512, NOT scalable Krylov eigs. Default k=min(6,n); explicit k is 1..n (only k=0 for n=0). which is exactly 'largestabs' (default) or 'smallestabs', ordered by absolute eigenvalue, descending or ascending. No generalized problem, shifts, nonsymmetric or complex input, tolerance/restart/options are supported.
One output is a REAL k-by-1 values column; two positions return REAL V n-by-k and D k-by-k with A*V approximately V*D. This differs from the general complex eig contract. Eigenvector signs/bases at repeated eigenvalues are not fixed. [~,D] avoids vectors but still validates/decomposes; scaling that erases a nonzero entry or an unrepresentable selected value errors. No arbitrary precision or universal dynamic-range guarantee.
A=[-5,0,0;0,2,0;0,0,1];
values=eigs(sparse(A),2);
disp(all(imag(values)==0) && all(size(values)==[2,1]) && all(abs(values-[-5;2])<1e-10));
[V,D]=eigs(A,2,'smallestabs');
disp(all(imag(V)==0) && all(imag(D)==0) && all(size(V)==[3,2]) && all(abs(A*V-V*D)<1e-10));
[~,onlyD]=eigs(A,2,'smallestabs');
disp(all(abs(onlyD-D)<1e-10) && abs(D(1,1)-1)<1e-10);PT: eigs real simetrico limitado
eigs(A[,k[,which]]) aceita matrizes quadradas reais finitas densas/esparsas com simetria EXATA apenas. Materializa reducao simetrica DENSA limitada via EVD auto-adjunta faer, ordem <=512; NAO e eigs Krylov escalavel. Padrao k=min(6,n); k explicito 1..n (somente k=0 para n=0). which exatamente 'largestabs' (padrao) ou 'smallestabs', ordem por valor absoluto decrescente ou crescente. Sem problema generalizado, shifts, entradas nao simetricas/complexas, tolerancia/restart/opcoes.
Uma saida e coluna REAL k por 1; duas posicoes retornam V REAL n por k e D REAL k por k, com A*V aproximadamente V*D. Difere do contrato complexo geral de eig. Sinais/bases em autovalores repetidos nao sao fixos. [~,D] evita vetores mas valida/decompoe; escala que apaga entrada nao zero ou valor selecionado irrepresentavel gera erro. Sem precisao arbitraria ou garantia universal de faixa dinamica.
A=[2,1;1,2];
[V,D]=eigs(sparse(A),2);
disp(all(imag(V)==0) && all(imag(D)==0) && all(abs(A*V-V*D)<1e-10));
small=eigs(A,1,'smallestabs');
disp(all(size(small)==[1,1]) && abs(small(1)-1)<1e-10);EN: Nonlinear systems and nonnegative least squares
[x,residual]=fsolve(fun,x0[,tol[,maxiter]]) uses Levenberg-Marquardt with finite-difference Jacobians, not a general constrained optimizer. x0 is a finite Number or nonempty real row/column vector of <=128 coordinates. The handle receives the original x0 shape; its finite real Number/vector residual must have exactly the same count. x preserves original shape and residual is always a column, NOT an exitflag. Defaults tol=1e-8 and maxiter=100 (integer 1..100000). Success requires every final absolute residual<=tol. Nonconvergence/errors return no partial success; at most 100000 callbacks total including finite-difference Jacobians and final checks.
[x,resnorm]=lsqnonneg(C,d[,tol]) uses NNLS on nonempty finite real DENSE C(m,n), d(m,1), n<=128, m*n<=16777216. Returns x n-by-1 >=0 and resnorm=sum((C*x-d).^2). Optional positive finite tol defaults 1e-8 and checks normalized KKT conditions; there is NO iteration argument. Dynamic-range loss/nonfinite resnorm/backend failure errors. Both calls have at most two outputs, including discard masks; handles use the same dispatcher. fsolve callbacks preserve user errors, cancellation and capture-by-value; cancellation is not catchable.
C and d share positive-scale normalization. Any originally nonzero entry whose normalized absolute value is below sqrt(MIN_POSITIVE) (~1.49e-154) raises an explicit dynamic-range error before backend products can underflow, independently of tol. For example, C=[1e200,0;0,1], d=[0;1] errors with both default tol and 1e-250 rather than falsely returning zero. KKT checks are numerical safeguards, not a formal optimality guarantee or arbitrary dynamic-range support.
target=[2,3];
fun=@(point) point-target;
[x,residual]=fsolve(fun,[0,0]);
disp(all(size(x)==[1,2]) && all(abs(x-target)<1e-7) && all(size(residual)==[2,1]) && all(abs(residual)<1e-7));
C=[1,0;0,1;1,1]; d=[1;2;3];
[z,resnorm]=lsqnonneg(C,d);
disp(all(z>=0) && size(z,2)==1 && all(abs(C*z-d)<1e-7) && abs(resnorm-sum((C*z-d).^2))<1e-10);PT: Sistemas nao lineares e minimos quadrados nao negativos
[x,residual]=fsolve(fun,x0[,tol[,maxiter]]) usa Levenberg-Marquardt com Jacobianas por diferencas finitas, nao otimizador geral com restricoes. x0 e Number finito ou vetor real linha/coluna nao vazio com <=128 coordenadas. Handle recebe forma original de x0; residual Number/vetor real finito tem exatamente a mesma contagem. x preserva forma original e residual e sempre coluna, NAO exitflag. Padroes tol=1e-8 e maxiter=100 (inteiro 1..100000). Sucesso exige cada residuo absoluto final<=tol. Nao convergencia/erros nao retornam sucesso parcial; ate 100000 callbacks totais incluindo Jacobianas numericas e verificacoes finais.
[x,resnorm]=lsqnonneg(C,d[,tol]) usa NNLS em C(m,n), d(m,1) DENSOS reais finitos nao vazios, n<=128, m*n<=16777216. Retorna x coluna n por 1 >=0 e resnorm=sum((C*x-d).^2). tol positivo finito opcional tem padrao 1e-8 e verifica KKT normalizado; NAO ha argumento de iteracoes. Perda por faixa dinamica/resnorm nao finito/falha do backend gera erro. Ambos tem ate duas saidas incluindo mascaras; handles usam mesmo dispatcher. Callbacks fsolve preservam erros do usuario, cancelamento e captura por valor; cancelamento nao e capturavel.
C e d compartilham normalizacao por escala positiva. Qualquer entrada originalmente nao zero cujo valor absoluto normalizado fique abaixo de sqrt(MIN_POSITIVE) (~1.49e-154) gera erro explicito de faixa dinamica antes de produtos do backend sofrerem underflow, independente de tol. Por exemplo, C=[1e200,0;0,1], d=[0;1] gera erro tanto com tol padrao quanto com 1e-250, sem retornar zero falso. Verificacoes KKT sao protecoes numericas, nao garantia formal de otimalidade nem suporte a faixa dinamica arbitraria.
[x,residual]=fsolve(@(point) point.^2-4,3);
disp(abs(x-2)<1e-7 && all(size(residual)==[1,1]) && abs(residual(1))<1e-8);
solver=@lsqnonneg;
[x,resnorm]=solver(eye(2),[-1;2],1e-8);
disp(all(x>=0) && all(abs(x-[0;2])<1e-7) && abs(resnorm-1)<1e-10);EN: Stiff initial-value problems with BDF
[T,Y]=ode15s(fun,tspan,y0[,reltol[,abstol]]) uses ivp adaptive BDF orders 1-5 with its accuracy-enhancement coefficients, NOT MATLAB ode15s/NDF. It shares the ode45/ode23 API: handle receives (Number time, COLUMN state) regardless of y0 orientation; derivative is a matching finite real vector or Number for one state. y0 is a finite Number/nonempty real vector. Defaults reltol=1e-6, abstol=1e-9, positive finite scalar Numbers only. One output is T column, not a solution struct; two give Y with times as rows and states as columns.
tspan is a finite strictly monotone vector of >=2 times with finite total span: two endpoints select adaptive times; more than two return the EXACT requested dense-output grid forwards or backwards. At most 100000 derivative callbacks, including finite-difference Jacobians, and 100000 accepted/rejected BDF step attempts; accepted-output steps also bounded. Combined T+Y<=16777216 elements and each dense Jacobian n*n<=16777216. Nonconvergence, bad callbacks or budget exhaustion error, including through masks/handles. No options struct, events, mass matrix, user Jacobian, DAE, PDE/BVP or delay equations.
grid=[0,0.01,0.05,0.1];
[T,Y]=ode15s(@(time,state) -100*state,grid,1);
disp(all(T==grid.') && all(size(Y)==[4,1]) && abs(Y(end)-exp(-10))<1e-5);
back=[0.1,0.05,0];
[T,Y]=ode15s(@(time,state) -state,back,exp(-0.1));
disp(all(T==back.') && abs(Y(end)-1)<1e-5);PT: Problemas de valor inicial rigidos com BDF
[T,Y]=ode15s(fun,tspan,y0[,reltol[,abstol]]) usa BDF adaptativo ivp de ordens 1-5 com coeficientes de melhoria de precisao, NAO ode15s/NDF do MATLAB. Compartilha API de ode45/ode23: handle recebe (tempo Number, estado COLUNA) independente da orientacao de y0; derivada e vetor real finito compativel ou Number para um estado. y0 e Number/vetor real finito nao vazio. Padroes reltol=1e-6, abstol=1e-9, apenas Numbers escalares positivos finitos. Uma saida e T coluna, nao struct de solucao; duas fornecem Y com tempos nas linhas e estados nas colunas.
tspan e vetor finito estritamente monotono de >=2 tempos com intervalo total finito: dois extremos selecionam tempos adaptativos; mais de dois retornam grade EXATA pedida por saida densa, crescente ou decrescente. Ate 100000 callbacks de derivada incluindo Jacobianas por diferencas finitas e 100000 tentativas BDF aceitas/rejeitadas; passos de saida aceitos tambem limitados. T+Y combinado<=16777216 elementos e cada Jacobiana densa n*n<=16777216. Nao convergencia, callback invalido ou orcamento esgotado gera erro inclusive via mascaras/handles. Sem struct de opcoes, eventos, matriz de massa, Jacobiana do usuario, DAE, EDP/PVC ou equacoes com atraso.
grid=[0,0.1,0.2];
solver=@ode15s;
[T,Y]=solver(@(time,state) -state,grid,[1,2]);
disp(all(T==grid.') && all(size(Y)==[3,2]) && all(abs(Y(end,:)-exp(-0.2)*[1,2])<1e-5));EN: Linear programming and execution boundaries
[x,fval]=linprog(f,A,b), linprog(f,A,b,Aeq,beq) or linprog(f,A,b,Aeq,beq,lb,ub): exactly 3/5/7 arguments, at most two outputs. Minimize f'*x subject to A*x<=b, Aeq*x=beq and lb<=x<=ub. [] omits constraint pairs/bounds; default lb=-Inf, ub=Inf, NOT implicit nonnegativity. f is a finite real nonempty vector/Number; constraint arrays are finite real DENSE matrices (Number for 1-by-1), RHS matching vectors. Bounds allow -Inf only on lower side and +Inf only on upper side, no NaN, lb<=ub. Output x is a column and fval a Number, not an exitflag or dual variables.
The objective and each inequality/equality row (including its RHS) are normalized by positive scales; nonzero entries must survive normalization and results must stay finite, otherwise a numerical-range error is raised. Tiny nonzero objectives are not treated as zero: linprog([1e-12],[],[]) and linprog([-1e-12],[],[]) error as unbounded. linprog([1],[-1e-12],-2e-12) returns x=2 and fval=2. Postchecks validate normalized constraints and finite bounds with scaled feasibility tolerance 1e-8; these are numerical safeguards, not a formal optimality guarantee. fval is computed with the original objective f, not its normalized coefficients.
microlp limits: <=128 variables, <=10000 combined inequality/equality rows, <=1000000 coefficients including objective and dense zero coefficients. A cooperative 5-second backend timeout is not a hard wall-clock deadline or immediate cancellation guarantee; infeasible, unbounded, timeout and nonfinite results error without partial optimum. All 11 Stage 5 builtins are initially BLOCKED in parfor, even issparse/nnz. LLVM rejects them: use sun run; sun check validates syntax/parallel restrictions, not runtime availability or numerical domains. Output positions/masks are checked before callbacks; discarded outputs still validate arguments and numerical convergence. Requires integrated runtime and rebuilt CLI; catalog parity must never filter missing names.
This stage does not implement fmincon, general constrained nonlinear optimization, PDE/BVP, delay equations, OOP or web FFI. Stages 1/2/3/4 retain their dense/data contracts; sparse does not expand mldivide/eig/NNLS/LP into general sparse dispatch. Studio read-only metadata is upcoming, not an editing promise.
[x,cost]=linprog([-1;-2],[1,1],3,[],[],[0;0],[]);
disp(all(size(x)==[2,1]) && all(x>=0) && sum(x)<=3+1e-8 && abs(cost+6)<1e-8);
[x,cost]=linprog([1],[-1],2);
disp(abs(x(1)+2)<1e-8 && abs(cost+2)<1e-8);
[~,cost]=linprog([1;2],[],[],[1,1],1,[0;0],[1;1]);
disp(abs(cost-1)<1e-8);PT: Programacao linear e fronteiras de execucao
[x,fval]=linprog(f,A,b), linprog(f,A,b,Aeq,beq) ou linprog(f,A,b,Aeq,beq,lb,ub): exatamente 3/5/7 argumentos, ate duas saidas. Minimiza f'*x sujeito a A*x<=b, Aeq*x=beq e lb<=x<=ub. [] omite pares de restricoes/limites; padrao lb=-Inf, ub=Inf, NAO nao negatividade implicita. f e vetor/Number real finito nao vazio; restricoes sao matrizes DENSAS reais finitas (Number para 1 por 1), RHS vetores compativeis. Limites aceitam -Inf apenas no inferior e +Inf apenas no superior, sem NaN, lb<=ub. x e coluna e fval Number, nao exitflag nem variaveis duais.
O objetivo e cada linha de desigualdade/igualdade (incluindo RHS) sao normalizados por escalas positivas; entradas nao zero devem sobreviver a normalizacao e resultados devem permanecer finitos, senao ocorre erro de faixa numerica. Objetivos nao zero diminutos nao viram zero: linprog([1e-12],[],[]) e linprog([-1e-12],[],[]) geram erro de problema ilimitado. linprog([1],[-1e-12],-2e-12) retorna x=2 e fval=2. Pos-checagens validam restricoes normalizadas e limites finitos com tolerancia de viabilidade escalada 1e-8; sao protecoes numericas, nao garantia formal de otimalidade. fval usa o objetivo f original, nao seus coeficientes normalizados.
Limites microlp: <=128 variaveis, <=10000 linhas combinadas de desigualdade/igualdade, <=1000000 coeficientes incluindo objetivo e zeros densos. Timeout cooperativo do backend de 5 segundos nao e prazo rigido de relogio nem garantia de cancelamento imediato; inviavel, ilimitado, timeout ou resultado nao finito gera erro sem otimo parcial. TODOS os 11 builtins da etapa 5 sao inicialmente BLOQUEADOS em parfor, mesmo issparse/nnz. LLVM rejeita: use sun run; sun check valida sintaxe/restricoes paralelas, nao disponibilidade ou dominio numerico. Posicoes/mascaras verificadas antes dos callbacks; saidas descartadas ainda validam argumentos e convergencia. Exige runtime integrado e CLI recompilado; nunca filtrar nomes ausentes na paridade do catalogo.
Etapa nao implementa fmincon, otimizacao nao linear geral com restricoes, EDP/PVC, equacoes com atraso, OOP ou web FFI. Etapas 1/2/3/4 preservam contratos densos/dados; sparse nao transforma mldivide/eig/NNLS/LP em dispatch esparso geral. Metadados somente leitura no Studio estao previstos, sem promessa de edicao.
solver=@linprog;
[x,cost]=solver([1;2],[],[],[1,1],1,[0;0],[1;1]);
disp(all(size(x)==[2,1]) && abs(sum(x)-1)<1e-8 && all(x>=0) && abs(cost-1)<1e-8);
[x,cost]=linprog([1],[-1],2,[],[]);
disp(abs(x(1)+2)<1e-8 && abs(cost+2)<1e-8);