如何从矩阵中删除坐标特定条目?

时间:2017-10-11 11:31:54

标签: matlab octave

我很难在Octave / Matlab中实现这个(貌似)简单的任务。

我想删除一组二维数据的特定条目。我有样本数据(x和y坐标的点),其中包含不应进一步处理的特定区域。我想从我的样本数据中删除这些区域。

以下是进一步了解我想要实现的内容的示例。我想:

B = A ,红色矩形中的数据除外

代码示例:

x = 0:pi/64:4*pi;
y = sin(x);

A = [x; y];

% Boundaries of the data that should be deleted
x1 = 4;
x2 = 6;
y1 = -1;
y2 = -0.5;

figure;
hold on;
plot(A(1,:),A(2,:),'bo');
plot([x1 x2 x2 x1 x1],[y1 y1 y2 y2 y1],'r-');

我知道如何选择红色矩形内的数据,可以使用以下命令完成:

indices = find(A(1,:)>x1 & A(1,:)<x2 & A(2,:)>y1 & A(2,:)<y2);
B(1,:) = A(1,indices);
B(2,:) = A(2,indices);
plot(B(1,:),B(2,:),'g-x');

但我需要相反:选择红色矩形外的数据。

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

反转语句中定义索引的所有运算符(即&gt;变为&lt;反之亦然,AND [&amp;]变为OR [|])。

indices2 = find(A(1,:)<x1 | A(1,:)>x2 | A(2,:)<y1 | A(2,:)>y2);
B=A(:,indices2);
plot(B(1,:),B(2,:),'g-x');

答案 1 :(得分:0)

使用逻辑阵列选择数据

管理选择的一种非常方便的方法是使用逻辑数组。这比使用索引更快,并且允许选择的简单反转以及多个选择的组合。这是修改后的选择功能:
sel = A(1,:)>x1 & A(1,:)<x2 & A(2,:)>y1 & A(2,:)<y2
结果是一个逻辑数组,它是一种非常有效的内存和快速的信息表示。

有关输出的图形表示,请参阅figure

代码示例

x = 0:pi/64:4*pi;
y = sin(x);
% Combine data: This is actually not necessary
% and makes the method more complicated. If you can stay with x and y
% arrays formulation becomes shorter
A = [x; y];

% Boundaries of the data that should be deleted
x1 = 4;
x2 = 6;
y1 = -1;
y2 = -0.5;

% Select interesting data
sel = A(1,:)>x1 & A(1,:)<x2 & A(2,:)>y1 & A(2,:)<y2;
% easily invert selection with the rest of data
invsel = ~sel;

% Get selected data to a new array
B1 = A(:,sel);
B2 = A(:,invsel);

% Display your data
figure;
hold on;
plot(B1(1,:),B1(2,:),'bo');
plot(B2(1,:),B2(2,:),'rx');

% Plot selection box in green
plot([x1 x2 x2 x1 x1],[y1 y1 y2 y2 y1],'g-');

图形结果

Graphical result of above sample script on selecting data