检测矩阵之间包含的值并应用校正 [英] Detect values enclosed between matrices and apply correction

查看:92
本文介绍了检测矩阵之间包含的值并应用校正的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,标题可能不够清楚,对此感到抱歉(如果不使用说明,就无法确定哪个是更好的标题).让我用语言更好地解释.

Firstly, the title is probably not clear enough, sorry for that (can't decide what's a better title without using explanation). Let me explain better in words.

假设我有一个矩阵

A=[
0 0 0 0 0 -1 -1 -1 1 1 1 1 0 0 0 0 0 1 1 1 -1 -1 -1 0 0 0 0 0
0 0 0 0 0 1 1 1 -1 -1 -1 -1 0 0 0 0 0 -1 -1 -1 1 1 1 0 0 0 0 ]

我要执行的操作是检测0与每行上的所有值之间的边界,并通过外壳将其分段.对于第1行,我有(0 -11 0)(0 1-1 0),因此我想使用此信息将边界内封闭的所有值校正为正值或负值,具体取决于它的开始位置与并以结束.例如,第一行将变成类似以下内容:

What I would like to this is detects the boundary between 0 and any values on per row and segment it by the enclosure. For row #1, I have (0 -1, 1 0), (0 1, -1 0), thus using this information I would like to correct all the values on enclosed inside that boundary to positive or negative values depending on what it begins with and ends with. For example, the first row would become somehting like:

[0 0 0 0 0 -1 -1 -1 -1 -1 -1 -1 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0]

任何可以有效执行此操作的想法,因为我要处理的矩阵非常大.预先谢谢您!

Any ideas that I can efficiently performs this because the matrix I'll be dealing with is of very large. Thanks you in advance!

编辑

附带的值不是必需的1.它可以是任何值范围[-1 1].

The enclosed values are not necessary 1. It can be any value ranges [-1 1].

推荐答案

以下是一种可能的解决方案:

Here is one possible solution:

% example matrix:
A=[
0 0 0 0 0 0.5 0.9 -1 0.1 0.3 1 1 0 0 0 0 0 0.9 -1 0.1 0.3 -1 -1 0 0 0 0 0;
0 0 0 0 0  0.1 0.3 1 -1 -1 -1 -1 0 0 0 0 0 -1 -1 -1 1 1 1 0 0 0 0 0 ];

[r,c]=find(A);
ind=sortrows([r c]);
steps=find(diff(ind(:,2))~=1);
steps=[[1; steps+1],[steps ;size(ind,1)]];
for k=1:size(steps,1)
  A(ind(steps(k,1),1),ind(steps(k,1),2):ind(steps(k,2),2))=A(ind(steps(k,1),1),ind(steps(k,1),2))
end

% result matrix:
A=
0   0   0   0   0.5 0.5 0.5 0.5 0.5 0.5 0.5 0   0   0   0   0   0.9 0.9 0.9 0.9 0.9 0.9 0   0   0   0   0
0   0   0   0   0.1 0.1 0.1 0.1 0.1 0.1 0.1 0   0   0   0   0   -1  -1  -1  -1  -1  -1  0   0   0   0   0

编辑

由于有了新的repelem,我提供了矢量化解决方案.现在,它可以在Matix A中用于连续索引,而不能用于行和列,因此我转置了A,以便通过矩阵的有趣序列将具有连续索引:

I came with a vectorized solution, thanks to the new repelem. Now it works with continuous indexing in the matix A, and not with row and column, so I transposed A so that the interesting sequences through the matrix will have continuous indices:

A=A.';
B=find(A);
steps=diff([0;find(diff(B)>1) ;length(B)]);
vals=A(B([0 ;find(diff(B)>1)]+1));
A(A~=0)=repelem(vals,steps);

这篇关于检测矩阵之间包含的值并应用校正的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆