How to select with several conditions in a matrix

조회 수: 2 (최근 30일)
Luisa Andrade
Luisa Andrade 2021년 11월 23일
편집: Luisa Andrade 2021년 11월 25일
I want to select the data from falling below -1 until it turns positive or crosses zero, at least two consecutive times.
An example to clarify what I mean:
In the following matrix I want to selec the bold numbers:
b = [-0.32 -0.5 -1.1 -1.9 -0.5 -0.1 0.2 NaN -1.20 NaN NaN; -0.32 -0.5 -1.1 -1.9 -0.5 -0.1 0.2 NaN -1.20 -0.9 NaN]';

채택된 답변

Image Analyst
Image Analyst 2021년 11월 23일
See if this is what you want:
b = [-0.32 -0.5 -1.1 -1.9 -0.5 -0.1 0.2 NaN -1.20 NaN NaN; -0.32 -0.5 -1.1 -1.9 -0.5 -0.1 0.2 NaN -1.20 -0.9 NaN]'
[rows, columns] = size(b)
bb = [0 0 0 0 0 0 0 0 0 0 0; 0 0 1 1 0 0 0 0 1 0 0]'
for col = 1 : columns
% Find out where this column is less than -1.
mask = b(:, col) < -1
% Find out the indexes where the runs below -1 start at.
startingIndexes = strfind(mask', [0, 1]) + 1
% Find out where this column is less than 0.
mask2 = b(:, col) < 0
for k = 1 : length(startingIndexes)
index1 = startingIndexes(k);
for row = index1 : rows
if mask2(row)
index2 = row;
else
break; % Went 0 or above so don't increment the second index.
end
end
% Set thos values of bb.
bb(index1:index2, col) = 1;
end
end
bb
  댓글 수: 4
Image Analyst
Image Analyst 2021년 11월 24일
Thanks for accepting. Though I was wondering why the last item, where the value is -1.2, you did not want to mark that location as 1. Is it because it did not go positive before it encountered a NaN?
Luisa Andrade
Luisa Andrade 2021년 11월 24일
Because of the second condition, "at least two consecutive times" ;)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2014b

Community Treasure Hunt

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

Start Hunting!

Translated by