Struggling newbie - Iterate over a 20000X2 array, then do math and create new array
Show older comments
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)
Wayne King
on 6 May 2012
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
Mark
on 7 May 2012
Sean de Wolski
on 7 May 2012
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!
Categories
Find more on Logical 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!