Index must be a positive integer or logical

1 view (last 30 days)
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.

Accepted Answer

the cyclist
the cyclist on 28 Sep 2014
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);
  2 Comments
Roberto
Roberto on 28 Sep 2014
I really want to thank you for the help! Actually this is my first assignment after only one lesson in front of MATLAB so I'm still not into it.
the cyclist
the cyclist on 28 Sep 2014
The best form of thanks here is accepting the Answer the most clearly solved your question for you. This both rewards the person who answered, and helps point others to potential solutions to their own issues.

Sign in to comment.

More Answers (0)

Categories

Find more on Parallel Computing in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!