I followed the instructions, but what I only can get is "error in (filename)" without any additional details. Could you tell me which part made an error?
clear;clc;lb = [0,0];
ub = [1,1];
A = [1 1];
B = [1];
Aeq = [];
Beq = [];
x0=[0.5, 0.5];
f=#(x)(200*x(1)-37)^2+(200*x(2)-83)^2+(200*x(1)+200*x(2)-122)^2+(400*x(1)-82)^2+(400*x(2)-157)^2+(400*x(1)+400*x(2)-250)^2;
x = fmincon(f,x0,A,B,Aeq,Beq,lb,ub)
this code is work fine, and this is the result:
x =
0.2090 0.4050
you needs to save your script file and add the folder contain your file to matlab "Add to path".
Related
This question contains a lot of code, but a lot of it is error messages and parameter definitions.
I am trying to generate a matlab function script to calculate the dynamics of a 4-link robot manipulator. The goal is to make the function take a bunch of parameters(vectors/matrices) as inputs and return system matrices D, C and G. All calculations are done symbolically according to standard formulas found in any robotics textbook. I have looked through all my calculations and find no errors here.
When the calculations are complete, the function file is generated by the following line of code:
matlabFunction(D,C,G,'File','getDynamicsFnc','Vars',{[q], [q_dot], [I1], [I2], [I3], [I4],
[th_a], [DH_params], [m], [com], [g]});
This leads to the following error message:
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
Error in sym/matlabFunction>computeVarnames (line 902)
allNames = matlab.lang.makeUniqueStrings([repelem("ft",1,nuOfBlocks-1), "ft"
allVars],1:nuOfBlocks-1,namelengthmax);
Error in sym/matlabFunction>postProcessing (line 826)
[newFunctionNames, newArgumentName] = computeVarnames(blocks);
Error in sym/matlabFunction (line 198)
blocks = postProcessing(blocks);
Error in generate_func_complete (line 119)
matlabFunction(D,C,G,'File','getDynamicsFnc','Vars',{[q], [q_dot], [I1], [I2], [I3], [I4],
[th_a], [DH_params], [m], [com], [g]});
I have checked the dimensions of all elements in the workspace and find no inconsistencies. I tried running the script with dummy-values for D, C and G and it worked properly (even when they were made up of elements from the transformation/Jacobi matricies that are calculated in the script).
The following code shows how D, C and G are calculated:
D = sym(zeros(dim)); C = sym(zeros(dim)); G = sym(zeros(dim,1));
% D matrix
for i = 1:dim % T{i} is a 4X4 matrix that was calculated previously
R = T{i}(1:3,1:3);
It = simplify(R*I{i}*R');
D = D + m(i)*J_v{i}'*J_v{i} + J_w{i}'*It*J_w{i}; % Calculate D
P = P + m(i)*gvec'*rc{i}; % Potential energy. Used to find G later
end
P = simplify(P);
% C matrix
for i= 1:dim
for j=1:dim
for k=1:dim
christ = 0.5*(diff(D(i,j),q(k)) + diff(D(i,k),q(j)) - diff(D(k,j),q(i))); % Calculating Christoffel symbols
C(i,j) = C(i,j) + christ*q_dot(k); % Summing Christoffel symbols to find elements of C
end
end
end
% G matrix
for i = 1:dim
G(i) = diff(P,q(i)); % Calculating G
end
I will not include calculations for T, J or rc due to the length of the code, but I have already verified that they are not the problem. All other parameters used are defined as follows:
dim = 4;
q = sym('q',[dim 1],'real');
q_dot = sym('q_dot',[dim 1],'real');
I1 = sym('I1', [3 3],'real');
I2 = sym('I2', [3 3],'real');
I3 = sym('I3', [3 3],'real');
I4 = sym('I4', [3 3],'real');
I = cell(1,4);
I{1} = I1; I{2} = I2; I{3} = I3; I{4} = I4;
th_a = sym('th_a','real');
DH_params = sym('DH_params', [5 4],'real');
com = sym('com', [5 3],'real');
m = sym('m', [1 dim],'real');
g = sym('g','real');
gvec = [0;0;g];
NOTE: I do not use the simplify function when calculating the outputs. This is due to the extreme increase in runtime for the script, to the point where it won't finnish over several hours.
I included a lot of code in this question, but I believe it is fairly simple to understand and hopefully not too exessive. Please give feedback if I overdid it.
I write code below but i find an error that I do not know what it is please help me
the error is
Error using idmodel/sim (line 114)
The simulation input data must be specified using an iddata object or a double
matrix.
Error in Untitled (line 17)
y = sim(sys,u);
clc;
clear all ;
close all;
A = [1 -0.5 0.06];
B = [5 -2];
C = [1 -0.2 0.001];
Ts = 1; %sample time
sys = idpoly(A,B,C,'Ts',1);
Range = [-1 1];
Band = [0 1];
u = stairs(idinput(100,'prbs',Band,Range)); %form a prbs input
opt1 = simOptions('AddNoise',true);
y = sim(sys ,u,opt1);
iodata = iddata(y,u,Ts);
na = 3; nb = 2; nc = 3; nk = 1;
me = armax(iodata,[na,nb,nc,nk]);
compare(iodata,me)
thank you very much
Your input variable u, should be a column vector, but with your code it is a graphics object, use class(u) to check this. If you replace this line
u = stairs(idinput(100,'prbs',Band,Range)); %form a prbs input
with something like this:
u = [zeros(25, 1); ones(25, 1)]; % step input
Then the code no longer crashes.
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 !
I have 4 data sets, and I need to perform linear regression on them. I keep getting errors in the matrices I've entered.
Here's what I tried to do: I entered the four different data sets as matrices and created a for loop that would go through each set of data and perform the same calculations on each one.
Not sure if my for loop will work - I have very very basic matlab knowledge and so any help would be appreciated!!
x{1} = [1; 2; 3];
y{1} = [2; 3; 4];
% Assume the following matrices are similar to the ones above
x{2} = [...];
y{2} = [...];
x{3} = [...];
y{3} = [...];
x{4} = [...];
y{4} = [...];
for i = 1:1:4
z = [ones(size(x(i))) x(i)];
a = z\y(i); % Line with error
St = sum((y(i)-mean(y(i))).^2);
Sr = sum((y(i)-(10^(a(1))*x(i).^a(2))).^2);
r2 = 1-Sr/St;
syx = sqrt(Sr/(length(x(i))-length(a)));
end
this is as suggested in the comments a matter of {} istead of (). Try:
z = [ones(size(x{i})) x{i}];
a = z\y{i};
I've got a problem with a parfor loop: when I want to run a code whose structure is very similar to that of the code shown below, I obtain the
Subscripted assignment dimension mismatch error
I run the code with
dbstop if error
and I've observed that the indexes i and j are well iterated but the results aren't avalaible to my wokspace. Do you have any idea?
matlabpool 12;
Nx = 51;
Ny = 53;
Nc = 11;
Ns = randn(Ny,Nx);
Nr = randn(Nc, 2^14);
Ne = randn(1, Nc);
parfor j = 1:Ny
tic
for i = 1:Nx
idx = randi([1,Nc],1,19);
if isempty(idx)
continue
end
a = Nr(idx,:);
b = Ne(idx)';
nrr = sum(bsxfun(#(a, b) a.*b, a, b)/(Ns(j,i)),1);
nrrr(j,i,:) = nrr;
end
toc
end
PS: This code isn't the real one but I can assure you that the types of operations are kept as those in the real one (the real one is found inside a very large script).