行和列
由于每个整数的输出都会发生变化,因此元胞数组将适合整个任务。对于整个矩阵,您可以执行以下操作:
A = randi(4,10,30); % some data
Row = repmat((1:size(A,1)).',1,size(A,2)); % index of the row
Col = repmat((1:size(A,2)),size(A,1),1); % index of the column
pos = @(n) [Row(A==n) Col(A==n)]; % Anonymous function to find the indices of 'n'
比你可以写的每个n:
>> pos(3)
ans =
1 1
2 1
5 1
6 1
9 1
8 2
3 3
. .
. .
. .
其中第一列是行,第二列是A 中每个n 实例的列。
对于所有ns,您可以使用arrayfun:
positions = arrayfun(pos,1:max(A(:)),'UniformOutput',false) % a loop that goes over all n's
或简单的for 循环(更快):
positions = cell(1,max(A(:)));
for n = 1:max(A(:))
positions(n) = {pos(n)};
end
两种情况下的输出都是元胞数组:
positions =
[70x2 double] [78x2 double] [76x2 double] [76x2 double]
对于每个n,你可以写positions{n},例如:
>> positions{1}
ans =
10 1
2 3
5 3
3 4
5 4
1 5
4 5
. .
. .
. .
仅行
如果您想要在每个给定行的列索引和n 中包含所有内容,您可以这样写:
A = randi(4,10,30);
row_pos = @(k,n) A(k,:)==n;
positions = false(size(A,1),max(A(:)),size(A,2));
for n = 1:max(A(:))
positions(:,n,:) = row_pos(1:size(A,1),n);
end
现在,positions 是一个逻辑 3-D 数组,每一行对应A 中的一行,每一列对应一个值n,第三维是组合的存在向量行和n。这样,我们可以将R定义为列索引:
R = 1:size(A,2);
然后找到给定行和n 的相关位置。例如,第 9 行 n=3 的列索引为:
>> R(positions(9,3,:))
ans =
2 6 18 19 23 24 26 27
这就像调用find(A(9,:)==3),但如果您需要多次执行此操作,查找所有索引并将它们存储在positions(这是合乎逻辑的,所以它不是那么大)会更快。