fog*_*rit 8 indexing matlab matrix addressing submatrix
我正在为MATLAB中这个非常简单的问题寻找一个优雅的解决方案.假设我有一个矩阵
>> M = magic(5)
M =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
Run Code Online (Sandbox Code Playgroud)
和形式的逻辑变量
I =
0 0 0 0 0
0 1 1 0 0
0 1 1 0 0
0 0 0 0 0
0 0 0 0 0
Run Code Online (Sandbox Code Playgroud)
如果我尝试检索与值M相关联的元素,我会得到一个列向量1I
>> M(I)
ans =
5
6
7
13
Run Code Online (Sandbox Code Playgroud)
[5 7 ; 6 13]从这个逻辑索引中获取矩阵的最简单方法是什么?
如果我知道非零元素的形状I,我可以在索引后使用重塑,但这不是一般情况.
另外,我知道MATLAB中这种索引类型的默认行为强制实现了非零值I不形成矩阵的情况的一致性,但我想知道是否有针对这种特殊情况的简单解决方案.
nrz*_*nrz 11
这是一种方法.假设所有行I具有相同数量的1.还假设I具有相同数字的所有列都具有1,因为Submatrix必须是矩形.
%# Define the example data.
M = magic(5);
I = zeros(5);
I(2:3, 2:3) = 1;
%# Create the Submatrix.
Submatrix = reshape(M(find(I)), max(sum(I)), max(sum(I')));
Run Code Online (Sandbox Code Playgroud)