问题描述
我在Matlab中有一个大小为Gx(l*N)
的矩阵Ksets
和一个大小为MxN
的矩阵A
.
I have a matrix Ksets
in Matlab with size Gx(l*N)
and a matrix A
with size MxN
.
Ksets
的每一行都可以分解为大小为1xN
的l
子行.
Each row of Ksets
can be decomposed into l
sub-rows with size 1xN
.
让我用一个例子更好地解释.
Let me explain better with an example.
clear
N=3;
l=4;
G=2;
M=5;
Ksets=[1 2 3 5 6 7 9 10 11 0 0 0;
13 14 15 1 2 3 21 22 23 1 1 1]; %Gx(l*N)
A=[1 2 3;
5 6 7;
21 22 23;
1 2 3;
0 0 0]; %MxN
在示例中:
-
行
1
由大小为1xN
的l
个子行组成:[1 2 3]
,[5 6 7]
,[9 10 11]
,[0 0 0]
;
Ksets
的row
1
ofKsets
is composed ofl
sub-rows with size1xN
:[1 2 3]
,[5 6 7]
,[9 10 11]
,[0 0 0]
;
行2
由大小为1xN
的l
个子行组成:[13 14 15]
,[1 2 3]
,[21 22 23]
,[1 1 1]
.
row 2
of Ksets
is composed of l
sub-rows with size 1xN
: [13 14 15]
, [1 2 3]
, [21 22 23]
, [1 1 1]
.
我假设Ksets
的每一行都不包含相等的子行.
I assume that each row of Ksets
does not contain equal sub-rows.
如果行A(m,:)
等于Ksets(g,:)
的l
子行之一,否则,我希望您的帮助以Response(g,m)=1
构造大小为GxM
的矩阵Response
.
I would like your help to construct a matrix Response
with size GxM
with Response(g,m)=1
if the row A(m,:)
is equal to one of the l
sub-rows of Ksets(g,:)
and zero otherwise.
继续上面的示例
Response= [1 1 0 1 1;
1 0 1 1 0]; %GxM
这段代码可以满足我的要求:
This code does what I want:
Responsecorrectmy=zeros(G, M);
for x=1:G
for c=1:l
Responsecorrectmy(x,:)=Responsecorrectmy(x,:)+...
ismember(A,Ksets(x,(c-1)*N+1:c*N), 'rows').';
end
end
我的代码包含2个循环,这是不希望的,因为在我的实际算法中,G,l
很大.您有没有循环的建议吗?
My code consists of 2 loops which is undesirable because in my real algorithm G,l
are big. Do you have suggestions without loops?
推荐答案
只需稍作调整即可进行尺寸调整:
It can be done with a little reshaping and dimension-permuting:
Response = permute(any(all(bsxfun(@eq, reshape(Ksets.', N, [], G), permute(A, [2 3 4 1])), 1), 2), [3 4 1 2]);
其工作原理如下:
-
reshape(Ksets.', N, [], G)
将Ksets
整形为N
×l
×G
3D阵列,以便每个子行现在都彼此分开. -
bsxfun(@eq, ..., permute(A, [2 3 4 1]))
创建一个N
×l
×G
×M
4D数组,其结果是将步骤1中的3D数组的每个元素与A
中的每个值进行比较. /li> -
all(..., 1)
测试每个子行(即第一维)的元素 all 是否匹配.any(...,2)
测试是否发生在原始行之一(即第二维)的任何子行中. -
permute(..., [3 4 1 2])
删除前两个维度(在步骤3中变为单例),从而提供所需的G
×M
结果. (为此使用squeeze
是不安全的,因为如果G=1
,它将错误地删除三维尺寸.)
reshape(Ksets.', N, [], G)
reshapesKsets
into anN
×l
×G
3D-array so that each subrow is now separated from the others.bsxfun(@eq, ..., permute(A, [2 3 4 1]))
creates anN
×l
×G
×M
4D-array with the result of comparing each element of the 3D-array from step 1 with each value inA
.all(..., 1)
tests if all the elements of each subrow (i.e. first dimension) match.any(...,2)
tests if this happens for any subrow of one of the original rows (i.e. second dimension).permute(..., [3 4 1 2])
removes the first two dimensions (which became singleton in step 3), giving the desiredG
×M
result. (It would not be safe to usesqueeze
for this because it would incorrectly remove the third dimension ifG=1
).
这篇关于查找矩阵中Matlab中的行是否“下降".在另一个矩阵的行内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!