I have coded an algorithm in MATLAB which contains a loop. The code works well for a number of iterations, then suddenly stops due to the following error
??? Index exceeds matrix dimensions.
What could be the cause of this error?
This is part of the code.
[x,fval,exitflag,output]=cplexmilp(f,Aineq,bineq,Aeq,beq,sostype,sosind,soswt,lb,ub,ctype,x0,options)
for m=1:100
supply=[];
supply=x(1:p*w*t);
supply=reshape(supply,w,p*t)';
Failprob=[0.1927 0.1753 0.1728 0.1165 0.2375 0.1649];%Low
%Failprob=[0.3770 0.3061 0.2894 0.2682 0.3993 0.2983];%Med
Failprob=[0.5708 0.4842 0.4097 0.5144 0.4205 0.4312];%High
%Failprob=[0.4547 0.4958 0.4965 0.4158 0.4971 0.4957];%High
Epsilon=[.8 .9];%Low
%Epsilon=[.7 .9];%Med
Epsilon=[.6 .9];%High
Sigma=.05;%Low
%Sigma=.10;%Med
Sigma=.2;%High
Failprob=Failprob';
prob2=1-Failprob;
prob2=horzcat(prob2,Failprob);
prob2=repmat(prob2,t,1);
for n=1:t
for i=1+p*(n-1):p+p*(n-1)
for j=1:w
r=rand;
prob=prob2(i,:);
prob=cumsum(prob);
value=[supply(i,j),(Epsilon(1)+(Epsilon(2)-Epsilon(1))*rand(1))*supply(i,j)];
%values corresponding to the probabilities
ind=find(r<=prob,1,'first');
supply(i,j)=value(ind);
end
end
end
After some iterations, I have the following output.
Iteration 20 Current value 12020253.6911 Best value 12020253.6911
Iteration 21 Current value 10841341.9259 Best value 10841341.9259
Iteration 22 Current value 11307742.3543 Best value 10841341.9259
Iteration 23 Current value 10784746.9812 Best value 10784746.9812
??? Index exceeds matrix dimensions.
Error in ==> CodefinalTwelveGuMulti at 1947
supply=x(1:p*w*t);
I don't even know how that code could even run. x is not defined anywhere and you suddenly are starting to use it in your for loop at the beginning. My guess is that you have some code defined somewhere earlier on, those iterations start happening and then once those iterations end, this function runs. That makes sense since I don't see any print-out statements anywhere in your code.
That's what the error is alluding to. It is stating that you are trying to index into x with indices that exceed the dimensions of x. In this case, x has no dimensions (i.e. empty). As such, no matter what indices you are using to try to index into x, MATLAB will give you an index exceeding error.
You need to either define x by providing it as an input into your function, or define it inside the function itself.
Related
I have to plot the solution for masses between 4 and 8kg, which I wrote using the code below:
weight=linspace(4,8,100)
Then I use a for loop to find the solutions for the weights within this vector, while also declaring the variable a, and a guess of the time required:
for z=1:length(weight)
a=(weight./(1360*pi)).^(1/3)
tguess=14400
timeinseconds=fsolve(#(t)cookingtimes(t,a),tguess)
timeinhours=timeinseconds/(60*60)
end
The function that I mentioned previously is below:
function F=cookingtimes(t,a)
k=1:22;
alpha=0.7*10^(-7);
F(1)=(2./(pi*0.464))*sum(((-1).^(k-1))./k).*sin(k*pi*0.464).*exp(((-(k.^2)).*(pi.^2).*((alpha.*t))./(a.^2)))-57/80
end
Where F(1) represents the following equation 1, which will be equal to 57/80. Rather than adding until infinity, I chose the value of 22 as the equation converges to this value. r/a is equal to 0.464, which is why this is present within my function.
When running this code, I am given errors that I cant manage to solve.
Arrays have incompatible sizes for this operation.
Error in Homework1>cookingtimes (line 58)
F(1)=(2./(pi*0.464))*sum(((-1).^(k-1))./k).*sin(k*pi*0.464).*exp(((-(k.^2)).*(pi.^2).*.((alpha.*t))./(a.^2)))-57/80
Error in Homework1 (line 28)
timeinseconds=fsolve(#(t)cookingtimes(t,a),tguess)
Error in fsolve (line 264)
fuser = feval(funfcn{3},x,varargin{:});
Caused by:
Failure in initial objective function evaluation. FSOLVE cannot continue.
The arrays that I have produced are all of the same length, which is why I am very stuck on this issue.
You are trying to perform an operation on two arrays that have different sizes. In your case, the issue may be caused by the fact that you are defining the variable a as a vector inside the for loop, but using it in the function cookingtimes as a scalar. To fix this, you can modify your function to accept a vector of a values and return a corresponding vector of function values.
I modified the cookingtimes function to accept a vector of a values, and return a corresponding vector of function values.
function F=cookingtimes(t,a)
k=1:22;
alpha=0.7*10^(-7);
F=(2./(pi*0.464))*sum(((-1).^(k-1))./k).*sin(k*pi*0.464).*exp(((-(k.^2)).* (pi.^2).*((alpha.*t))./(a.^2)))-57/80;
end
In the for loop, You need to compute a for each weight value, and use a vector of a values in the call to fsolve. Also store the solutions in a vector timeinseconds instead of a scalar, as there are multiple solutions to be found.
for z=1:length(weight)
a=(weight(z)./(1360*pi)).^(1/3); % compute a for each weight value
tguess=14400;
timeinseconds(z)=fsolve(#(t)cookingtimes(t,a),tguess);
timeinhours=timeinseconds/(60*60);
end
I am trying to create piecewise functions V(t), D(t).
I try to find the piecewise, then I use the piecewise of t to construct functions and plot them.
But it shows "Index exceeds the number of array elements. Index must not exceed 51".
How can I fix it?
I put my code below and I really hope someone can answer it. Thaks!
z=zeros(1,50);
p_i=zeros(1);
p=0.023;
for i=1:50
z(i)=rand;
if z(i)>p
p_i(end+1)=i+z(i);
end
end
n=numel(p_i);
V=zeros(1,n);
w=zeros(1,n);
D=zeros(1,n);
V_op=zeros(1,n);
%get the number of pi
sigma_w0=0.2;
Q=5;
P=2;
Q_op=4;
for i=1:n
if i>1
w(i)=w(i-1)+normrnd(0,sigma_w0);
V(i)=Q*w(i);
D(i)=P*w(i);
V_op(i)=Q_op*w(i);
else
w(1)=2;
V(i)=Q*w(i);
D(i)=P*w(i);
V_op(i)=Q_op*w(i);
end
end
t=0:0.0002:50;
V_p=zeros(size(t));
D_p=zeros(size(t));
V_opp=zeros(size(t));
for m=1:length(t)
t(m)>=p_i(i)& t(m)<p_i(i+1)
V_p(m)=V(i);
D_p(m)=D(i);
V_opp(m)=V_op(i);
end
Yes, if you run your code you'll see it is functional before the last for loop since it is evaluating that in the 1 to 50 range (m=1:length(t)) but your line is printing 51 values so you need to check only the next part and reorganize the idea:
t(m)>=p_i(i)& t(m)<p_i(i+1)
If you print the first part (t(m)>=p_i(i)) it is okay, but check the other part and you'll notice the error. Maybe you can print all your results moving your increment value (+1) and prevent it from exceeding 1 to 51.
I am tagging my question and code along with output please into it tell where I did wrong.
Write a function
function p=r1p(a,n,x)
that computes and return p=P*x where P is a 2x2 projection matrix of rank 1
with column space consisting of the scalar multiples of a and
with null space consisting of the scalar multiples of n.
Notes:
The function must be named r1p
a is a nonzero column vector with two components.
n is a nonzero column vector with two components.
x is a nonzero column vector with two components.
My code:
function p = r1p(a,n,x)
% computes the action of P, the 2x2 projection matrix of rank 1 having
% a as an eigenvector with eigenvalue 1 and
% n as an eigenvector with eigenvalue
a=[1; 0.01]
n=[0.01; 1]
x=[1; 0]
p=r1p(a,n,x)
end
Error:
Out of memory. The likely cause is an infinite recursion within the program.
Error in r1p (line 8)
p=r1p(a,n,x)
from the reason that are described in the comment, the function just calls itself each time. The stack, which is a memory that holds details about all the chain of function calls, just fills up till it catch the whole allocated memory, and can't make more call since there is no memory to write the additional call.
It seems that you are missing the point of the recursion. On each stage, the input for the recursion should be changed, getting closer to a "basic" input that will be calculated directly. So this is a stage that is missing at your code - the recursive call for the function must be under a certain condition, and this condition should be fulfilled in some stage.
in addition, it seems that your function does not perform any calculation with your inputs.
see here a simple example:
myFactorial = factorial(5)
function output=factorial(input)
if (input<=0)
output=1;
else
output=input*factorial(input-1);
end
end
you can see that:
the internal call for factorial is under condition
the input is decreased so finally the input is 1 and the function is not called again.
there is an internal calculation, that implements what the programmer wanted.
I am aware that dozens of threads have been started about this particular error, but none of them actually answer the problem I'm having.
I'm trying to generate a plot of voltage spikes at given intervals using the following code:
V=zeros(1:NN);
nspace=50; % Spacing of the spikes in angstroms
V0=-0.1*eV2J; % magnitude of the voltage spikes
for n=10/nspace:NN:nspace
V(nspace*n)=V0;
end
The variables NN and eV2J are already defined earlier in the code.
Now, here's the problem I'm having that the other threads don't answer. The indexing error only pops up for certain values of nspace, but not for others. For example, this block of code executes just fine for...
nspace = 20,23,24,27,29,31,32,33,34,36,37,38,40
...but the error occurs for all other integer values between 20 and 40, and this seemingly random distribution of acceptable values continues on past 40 as well. The index generated for all of these values are indeed integers (starting at 10 and incrementing by nspace each loop).
Every thread I've seen for this error states that is occurs when a variable sharaes a name with a built in MATLAB function, or when the index is not a positive real integer or logical. That is clearly not the case here.
Any ideas?
here is the code listing and i got the above mentiond error at line nests(r,c)=nests(r,c)+stepsize.*randn(size(nests(r,c))); please let me now what is wrong with my code as i m new to matlab
for r = 1:numb_of_nest % for each particle
for c = 1:4
u=randn(size(nests(r,c)))*sigma;
v=randn(size(nests(r,c)));
step=u./abs(v).^(1/beta);
nests(r,c)=nests(r,c)+stepsize.*randn(size(nests(r,c)));
% Apply simple bounds/limits
ns_tmp=nests(r,c);
I=ns_tmp<Lb(c);
ns_tmp(I)=Lb(I);
% Apply the upper bounds
J=ns_tmp>Ub(c);
ns_tmp(J)=Ub(J);
% Update this new move
nests(r,c)=ns_tmp;
end
end
This error happens when you assign a value of some dimension m x n to a subscripted variable of different dimension.
In your case, assuming nests has no third dimension, you're assigning to a scalar (1x1) variable. This only works if the value you're trying to assign also is a scalar. Since you get the error, it probably isn't. The only place where your dimensions can be non-scalar is stepsize, so to fix this error, make sure stepsize is a scalar value.
According to the definition you gave in an earlier comment (stepsize=0.01*step.*(nests(r,c)-best);), this problem translates to make sure best is a scalar value. Possibly by subscripting, I can't tell you exactly how since I don't know what best is.
step=u./abs(v).^(1/beta);
nests(r,c)=nests(r,c)+stepsize.*randn(size(nests(r,c)));
Here you're assigning a value to the variable step, but then using a different variable called stepsize that hasn't been assigned a value anywhere in this code. Is this intentional? If not, stepsize is probably some leftover variable from previous code which is messing up the dimensions and giving you this error.
In addition to the above, is nests an ordinary two-dimensional matrix in your code? If so, taking size(nests(r,c)) every time is unnecessary - since you're giving two subscripts, the result is only going to be 1 all the time. Or is nests a cell array perhaps? In that case, you might want to index using curly braces { } instead of ordinary parantheses, to get the size of the matrix that's sitting inside the cell.