MATLAB: Index must be a positive integer or logical

newbie question positive integer or logica

Hello everybody! My name is Roberto and I'm totally new with MATLAB which I'm now using for the first time in my econometric's class. I was asked to resolve this exercise: " 1) Generate 10000 normally distributed (0,1) observation X " 2) Compute the fraction of observed values above 1.95 or below -1.95.
While first point I haven't had any kind of problems, I found some in writing the looping code for the second point of the exercise. In particular, what I wrote is:
x=randn(10000,1)
for i=-1.95:1.95
if x(i,1)>=1.95 | x(i,1)<=-1.95
x(i,1)=1
else
y(i,1)=2
end
end
When I execute the code, MATLAB returns me the error:
"Attempted to access x(-1.95,1); index must be a positive integer or logical."
As I said before, I'm totally new to the world of MATLAB and its programming code. I really hope you can help me with this absolutely stupid problem.

Best Answer

There are a couple issues with your code, but the main one with the for loop is that I think you intended to run it from 1:10000 (i.e. over each element of the array). So this version fixes that:
x=randn(10000,1);
for i=1:10000
if x(i,1)>=1.95 | x(i,1)<=-1.95
x(i,1)=1;
else
y(i,1)=2;
end
end
But you seem to have two other problems. First, why are you assigning values to both x and y inside your if statement? Guessing that is a mistake.
Why are you assigning values of 1 and 2, rather than 0 and 1? Guessing that is a mistake.
You are not taking advantage of MATLAB ability to do vectorized calculations. (Not exactly a mistake, but just that you are still learning MATLAB.) Check this out:
x=randn(10000,1);
y_vectorized = (x >= 1.95) | (x <= -1.95);