Selecting values in an array
36 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(2 个)
Geoff
2012-4-10
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 |.
0 个评论
Image Analyst
2012-4-10
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operators and Elementary Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!