Why is this for loop giving me an error? - matlab

So I am trying to go through a for loop that will increment .1 every time and will do this until the another variable h is less than or equal to zero. Then I am suppose to graph this h variable along another variable x. The code that I wrote looks like this:
O = 20;
v = 200;
g = 32.2;
for t = 0:.1:12
% Calculate the height
h(t) = (v)*(t)*(sin(O))-(1/2)*(g)*(t^2);
% Calculate the horizontal location
x(t) = (v)*(t)*cos(O);
if t > 0 && h <= 0
break
end
end
The Error that I keep getting when running this code says "Attempted to access h(0); index must be a positive integer or logical." I don't understand what exactly is going on in order for this to happen. So my question is why is this happening and is there a way I can solve it, Thank you in advance.

You're using t as your loop variable as well as your indexing variable. This doesn't work, because you'll try to access h(0), h(0.1), h(0.2), etc, which doesn't make sense. As the error says, you can only access variables using integers. You could replace your code with the following:
t = 0:0.1:12;
for i = 1:length(t)
% use t(i) instead of t now
end
I will also point out that you don't need to use a for loop to do this. MATLAB is optimised for acting on matrices (and vectors), and will in general run faster on vectorised functions rather than for loops. For instance, your equation for h could be replaced with the following:
O = 20;
v = 200;
g = 32.2;
t = 0:0.1:12;
h = v * t * sin(O) - 0.5 * g * t.^2;
The only difference is that you have to use the element-wise square (.^2) rather than the normal square (^2). This means that MATLAB will square each element of the vector t, rather than multiplying the vector t by itself.

In short:
As the error says, t needs to be an integer or logical.
But your t is t=0:0.1:12, therefore a decimal value.
O = 20;
v = 200;
g = 32.2;
for t = 0:.1:12
% Calculate the height
idx_t = 1:numel(t);
h(idx_t) = (v)*(t)*(sin(O))-(1/2)*(g)*(t^2);
% Calculate the horizontal location
x(idx_t) = (v)*(t)*cos(O);
if t > 0 && h <= 0
break
end
end
Look this question's answer for more options: Subscript indices must either be real positive integers or logical error

Related

Finding the maximum value from an expression using a loop in Matlab

I want to find the maximum value using the second derivative of the the expression when x is between 0 and 1. In other words I am taking the derivative of cox(x^2) twice to get the second derivative resulting in - 2*sin(x^2) - 4*x^2*cos(x^2), then I want to evaluate this second derivative at x = 0 to x = 1, and display the maximum value of the populated values.
I have:
syms x
f = cos(x^2);
secondD = diff(diff(f));
for i = 0:1
y = max(secondD(i))
end
Can someone help?
You can do it easily by subs and double:
syms x
f = cos(x^2);
secondD = diff(diff(f));
% instead of the for loop
epsilon = 0.01;
specified_range = 0:epsilon:1;
[max_val, max_ind] = max(double(subs(secondD, specified_range)));
Please note that it is a numerical approach to find the maximum and the returned answer is not completely correct all the time. However, by increasing the epsilon, you can expect a better result in general (again in some cases it is not completely correct).

Metropolis-Hastings in matlab

I am trying to use the Metropolis Hastings algorithm with a random walk sampler to simulate samples from a function $$ in matlab, but something is wrong with my code. The proposal density is the uniform PDF on the ellipse 2s^2 + 3t^2 ≤ 1/4. Can I use the acceptance rejection method to sample from the proposal density?
N=5000;
alpha = #(x1,x2,y1,y2) (min(1,f(y1,y2)/f(x1,x2)));
X = zeros(2,N);
accept = false;
n = 0;
while n < 5000
accept = false;
while ~accept
s = 1-rand*(2);
t = 1-rand*(2);
val = 2*s^2 + 3*t^2;
% check acceptance
accept = val <= 1/4;
end
% and then draw uniformly distributed points checking that u< alpha?
u = rand();
c = u < alpha(X(1,i-1),X(2,i-1),X(1,i-1)+s,X(2,i-1)+t);
X(1,i) = c*s + X(1,i-1);
X(2,i) = c*t + X(2,i-1);
n = n+1;
end
figure;
plot(X(1,:), X(2,:), 'r+');
You may just want to use the native implementation of matlab mhsample.
Regarding your code, there are a few things missing:
- function alpha,
- loop variable i (it might be just n but it is not suited for indexing since it starts at zero).
And you should always allocate memory in matlab if you want to fill it dynamically, i.e. X in your case.
To expand on the suggestions by #max, the code appears to work if you change the i indices to n and replace
n = 0;
with
n = 2;
X(:,1) = [.1,.1];
It would probably be better to assign X(:,1) to random values within your accept region (using the same code you use later), and/or include a burn-in period.
Depending upon what you are going to do with this, it may also make things cleaner to evaluate the argument to sin in the f function to keep it within 0 to 2 pi (likely by shifting the value by 2 pi if it exceeds those bounds)

Matlab Piecewise Transfer Function

I'm trying to set up a piecewise transfer function of a filter in matlab to get its impulse response. I have the code below:
function H = H(w)
H = zeros(size(w)); % Preallocating enough memory for y
nd = 0;
region1 = (abs(w)<(pi/4)) & (abs(w)>(pi/8)) ; % First interval
H(region1) = exp((-(w(region1))*1i*nd));
region2 = (abs(w)<(7*pi/8)) & (abs(w)>(5*pi/8)); % Second interval
H(region2) = exp((-0.5*(w(region1))*1i*nd));
region3 = ~(abs(w)<(pi/4)) & (abs(w)>(pi/8)) & ~(abs(w)<(7*pi/8)) & (abs(w)>(5*pi/8)) ; % Third interval
H(region3) = 0;
But it gives me this error, when I try to run:
In an assignment A(I) = B, the number of elements in B and I must be the same.Error
in H (line 9)
H(region2) = exp((-0.5*(w(region1))*1i*nd));
Am I going about this the right way or is there an easier way to do something like this?
I think the problem is that:
H(region2) = exp((-0.5*(w(region1))*1i*nd));
Should be:
H(region2) = exp((-0.5*(w(region2))*1i*nd));
Where region1 is corrected as region2.
Also, nd is always 0.
You ask if you're going about it the right way, seems decent enough to me as long as you realize the frequency response between the points you specify could be all over the place, or not depending on the transitions.

how do I compute this infinite sum in matlab?

I want to compute the following infinite sum in Matlab, for a given x and tau:
I tried the following code, given x=0.5 and tau=1:
symsum((8/pi/pi)*sin(n*pi*0.5)*sin(n*pi*0.5)*exp(-n*n*pi*pi)/n/n,1,inf)
But I get this:
(228155022448185*sum((exp(-pi^2*n^2)*((exp(-(pi*n*i)/2)*i)/2 - (exp((pi*n*i)/2)*i)/2)^2)/n^2, n == 1..Inf))/281474976710656
I want an explicit value, assuming the sum converges. What am I doing wrong? It seems like Matlab doesn't compute exp() when returning symsum results. How do I tell Matlab to compute evaluate the exponentials?
Convert to double
double(symsum(...))
Just to show you a different way, one that does not require the symbolic toolbox,
summ = 0;
summP = inf;
n = 1;
while abs(summP-summ) > 1e-16
summP = summ;
summ = summ + sin(n*pi*0.5)*sin(n*pi*0.5)*exp(-n*n*pi*pi)/n/n;
n = n + 1;
end
8/pi/pi * summ
which converges after just 1 iteration (pretty obvious, since exp(-4*6.28..)/n/n is so tiny, and sin(..) is always somewhere in [-1 1]). So given tau==1 and x==0.5, the infinite sum is essentially the value for n==1.
You should first define your variable "n" using syms. Then, you can include this variable in your symsum code.
Here's what I did:
syms n; AA = symsum((8/pi/pi)*sin(n*pi*0.5)*sin(n*pi*0.5)*exp(-n*n*pi*pi)/n/n,n,1,inf); BB = double(AA)
BB = 4.1925e-05

Compute the convolution of two arrays in MATLAB

I am trying to generate an array from some starting values using this formula in MATLAB:
yt = a0 + ∑i=1p (ai ⋅ yt-i), t ≥ p
p is some small number compared to T (max t). I have been able to make this using two for cycles but it is really slow. Is there some easy way to do it?
First p values of y are provided and vector a (its length is p+1) is provided too...
This is what I have so far, but now when I tried it, it doesn't work 100% (I think it's because of indexing from 1 in MATLAB):
y1 = zeros(T+1, 1);
y1(1:p) = y(1:p);
for t = p+1:T+1
value = a1(1);
for j = 2:p+1
value = value + a1(j)*y1(t-j+1);
end
y1(t) = value;
end
EDIT: I solved it, I am just not used to Matlab indexing from 1...
This statement
if(p>=t)
looks odd inside a loop whose index expression is
for t = p+1:T+1
which seems to guarantee that t>p for the entire duration of the loop. Is that what you meant to write ?
EDIT in response to comment
Inside a loop indexed with this statement
for j = 2:p
how does the reference you make to a(j) ever call for a(0) ?
y1 = zeros(T+1, 1);
y1(1:p) = y(1:p);
for t = p+1:T+1
value = a1(1);
for j = 2:p+1
value = value + a1(j)*y1(t-j+1);
end
y1(t) = value;
end