Selecting values in an array

36 views (last 30 days)
Trader
Trader on 10 Apr 2012
if I have an structure called results with arrays 'position' and 'profit', how can I build an array when, at the same time, position = 1 and profit = a positive double value. How about when profit = a negative value?
results =
position: [368x1 double]
profit: [368x1 double]
sample data:
x = [results.position, results.profit]
x =
-1 0
-1 12.265
1 0
1 -10.01
1 10.11
Thank you for your help.

Answers (2)

Geoff
Geoff on 10 Apr 2012
Logical indexing:
xfiltered = x( x(:,1)==1 & x(:,2)>0, : );
I'm sure you can work out the variations on this.
You can use 'OR' instead of 'AND' by replacing & with |.

Image Analyst
Image Analyst on 10 Apr 2012
Try this:
% Create sample data.
results.position = [-1 -1 1 1 1]';
results.profit = [0 12.265 0 -10.01 10.11]';
% Show all the data.
x = [results.position, results.profit]
% Create logical indexes for the various requested criteria.
positivePositionIndexes = results.position > 0
positiveProfitIndexes = results.profit > 0
negativeProfitIndexes = results.profit < 0
% Now create the output array for the two scenarios.
% Case 1: both position and profit must be positive.
case1Indexes = positivePositionIndexes & positiveProfitIndexes;
case1 = [results.position(case1Indexes), results.profit(case1Indexes)]
% Case 2: position must be positive and profit must be negative.
case2Indexes = positivePositionIndexes & negativeProfitIndexes;
case2 = [results.position(case1Indexes), results.profit(case2Indexes)]
In the command window:
case1 =
1.0000 10.1100
case2 =
1.0000 -10.0100

Categories

Find more on Operators and Elementary Operations in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!