“Index exceeds the number of array elements” for piecewise function - matlab

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.

Related

Matlab roll one dice game by using python and for sentence to add number

The question is this. As a result of consideration, I think if this condition is satisfied the code will be success.
Set n = 0, generate one of the integers 1~6 uniformly, Add a win if 1 was generated and add a lose otherwise, n++, 4. go back to 1 if n
but I don't know how to make it.can you please help me
N=100;
win=0;
lose=0;
a=randi([1 6],1,1);
n=0;
p=0;
while n<N
if a==1
win=win+1;
else
lose=lose+1;
n++
endif
endwhile
There are a couple of errors in your code:
you are generating only one random number, since the call to randi is outside of the while loop. So you are testing a==1 N times with a having always the same value
a part from the previous error, you are incrementing the counter n only in the else condition
A possible implementation could be the following in which you can incluide the code in a for loop to check the percentage of win wrt the number of attempts; you can also add the reference value of 1/6 %.
% Define the winning number
win_value=1
for N=1:1000
% Generate N random values
result=accumarray(randi([1 6],N,1),1);
% Count the wins
win(N)=result(win_value);
Pct_win(N)=win(N)/N*100;
end
plot(Pct_win)
hold on
plot([1 N],[1/6 1/6]*100,'r','linewidth',2)
xlabel('Attempts')
ylabel('Win %')
legend('Wins','Ref')

Matlab index error

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.

complex matlab for loop with matrix

I don't understand this piece of code of a for loop in matlab, I know that loops in matlab usually look like: for ii=1:2:100 so that it starts in 1 until 100 and in each iteration you add 2.
But here I've got this condition in the loop and I don't get what it does:
for ii=[1:w:rd(1)-w-border, rd(1)-w-border+1],
...
end;
w and border are integers passed as arguments and rd is size of the image/matrix (rd = size(image);)
Can someone explain me how for loops work in matlab with this kind of condition?
Thanks in advance.
For loop in matlab can execute statements for a defined set of index values:
For example, the following code will display all the element in the set [1,5,8,17]:
for s = [1,5,8,17]
disp(s)
end
Your code for ii=[1:w:rd(1)-w-border, rd(1)-w-border+1] is similar.
Its just like a set 1:w:rd(1)-w-border with an additional element rd(1)-w-border+1.
Its like writing this set [1,2,3,4,5,8] as [1:1:5, 8]
I hope its clear now.
the for argument is a vector. the loop iterator ii takes one value for the vector for each iteration of the loop. As you mentioned, the vector can be equally spaced one like 1:2:100. But it can also be arbitrary, for example for ii = [4,6,1,8] ....
In you case the for argument vector is partly "equally spaced" vector: 1:w:rd(1)-w-border plus another element rd(1)-border+1.

plotting from a loop

for t=0:0.1:10;
VS=3*exp(-t/3).*sin(t*pi);
if VS>0
VL(t+1)=VS;
else
VL(t+1)=0;
end
end
plot(0:100,VL);
xlabel('Time(s)')
ylabel('Across Voltage(V)')
title('Across Voltage Vs Time')
how to plot this figure based on VL (based on the relationship with VS whose expression shows above) versus t(from 0 to 10, increment 0.01)?
always got the error from matlab "Subscript indices must either be real positive integers or logicals."
Thanks.
There is a problem in your script. Note that t is defined in 0.1 intervals. Therefore, it is a real variable and can't be used as a subscript indice.
One way to solve that is
1) write cont=0; before the loop for.
2) write cont=cont+1 in the beginning of the loop
3) replace VL(t+1) by VL(cont)in both places inside the loop

MATLAB runs out of memory during program execution

I have been happily using MATLAB to solve some project Euler problems. Yesterday, I wrote some code to solve one of these problems (14). When I write code containing long loops I always test the code by running it with short loops. If it runs fine and it does what it's supposed to do I assume this will also be the case when the length of the loop is longer.
This assumption turned out to be wrong. While executing the code below, MATLAB ran out of memory somewhere around the 75000th iteration.
c=1;
e=1000000;
for s=c:e
n=s;
t=1;
while n>1
a(s,t)=n;
if mod(n,2) == 0
n=n/2;
else
n=3*n+1;
end
a(s,t+1)=n;
t=t+1;
end
end
What can I do to prevent this from happening? Do I need to clear variables or free up memory somewhere in the process? Will saving the resulting matrix a to the hard drive help?
Here is the solution, staying as close as possible to your code (which is very close, the main difference is that you only need a 1D matrix):
c=1;
e=1000000;
a=zeros(e,1);
for s=c:e
n=s;
t=1;
while n>1
if mod(n,2) == 0
n=n/2;
else
n=3*n+1;
end
t=t+1;
end
a(s)=t;
end
[f g]=max(a);
This takes a few seconds (note the preallocation), and the result g unlocks the Euler 14 door.
Simply put, there's not enough memory to hold the matrix a.
Why are you making a two-dimensional matrix here anyway? You're storing information that you can compute just as fast as looking it up.
There's a much better thing to memoize here.
EDIT: Looking again, you're not even using the stuff you put in that matrix! Why are you bothering to create it?
The code appears to be storing every sequence in a different row of a matrix. The number of columns of that matrix will be equal to the length of the longest sequence currently found. This means that a sequence of two numbers will be padded with a bunch of right hand zeros.
I am sure you can see how this is incredibly inefficient. That may be the point of the exercise, or it will be for you in this implementation.
Better is to keep a variable like "Seed of longest solution found" which would store the seed for the longest solution. I would also keep a "length of longest solution found" keep the length. As you try every new seed, if it wins the title of longest, then update those variables.
This will keep only what you need in memory.
Short Answer:Use a 2d sparse matrix instead.
Long Answer: http://www.mathworks.com/access/helpdesk/help/techdoc/ref/sparse.html