Struggling newbie - Iterate over a 20000X2 array, then do math and create new array

Hello, I am a matlab programming newbie, as well as a programming newbie. I feel certain my question has been asked and answered many times, but I'm not certain what terms to use to search for the answer. I have a text file that contains a 20000x2 array. The first column is an x-coordinate and the second column is its associated y-coordinate. I want to confirm that each x-coordinate and each y-coordinate fall within a range. For data points that pass the test I want to store the ratio y divided by x in a new vector. In other words, create one new vector that has the y/x ratio for each datapoint that passed the test.
In english, here are the steps I would perform. 1) Examine the first x,y coordinate. 2) If x is between 0 and 262143 and y is between 0 and 262143, then divide y by x. 3) Create a vector to store the y/x values.

Answers (1)

One of many ways:
%just creating some data because I do not have your data
X = randi([-262143 262143],2e4,2);
% substitute your data for X
xindex = find(X(:,1)>0 & X(:,1) < 262143);
yindex = find(X(:,2)>0 & X(:,2) < 262143);
indices = intersect(xindex,yindex);
Y = X(indices,:);
Y = Y(:,2)./Y(:,1);
Y is the vector with y/x

2 Comments

Dear Mr. King,
Thank you so much. I hope I can ask one question about this solution. I know about the find command already. I can see that xindex contains all of the x-coordinates that fall in the range and that yindex contains all of the y-coordinates that fall in the range. However, once those values are put into xindex and yindex they are no longer paired with their other coordinate, ie, the x-coordinate gets stripped away from its y-coordinate, and vice versa. I see that in the third line you created a variable called indices that applies a function intersect to the variables xindex and yindex. Is it the intersect command that properly pairs the x and y coordinates together again, and if so, how does it do that?
Thanks in advance!
Mark
INTERSECT() returns the indices in both xindex and yindex. Thus he finds the first column that meet the criters (xindex) the second column that meet the criteria (yindex) and then finds the ones that are in both.
he could skip the call to find and just use logical indexing:
indices = all(X>0&X<237637,2)
Which will be a list of logical indices.
find(indices) would return the linear indices.
Welcome to MATLAB and MATLAB Answers!

Sign in to comment.

Asked:

on 6 May 2012

Community Treasure Hunt

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

Start Hunting!