我有一個矩陣:Matlab的:找到行的索引與普通元素
1 2 3
4 5 6
7 8 1
我可以怎樣利用MATLAB來找到這樣的:對於第1行
:ROW3
爲第二排:---
爲第3行:行1
我想有行索引爲每行女巫有共同的元素。
我有一個矩陣:Matlab的:找到行的索引與普通元素
1 2 3
4 5 6
7 8 1
我可以怎樣利用MATLAB來找到這樣的:對於第1行
:ROW3
爲第二排:---
爲第3行:行1
我想有行索引爲每行女巫有共同的元素。
考慮這個
A = [1 2 3; %Matrix A is a bit different from yours for testing
4 5 6;
7 8 1;
1 2 7;
4 5 6];
[row col] =size(A)
answers = zeros(row,row); %matrix of answers,...
%(i,j) = 1 if row_i and row_j have an equal element
for i = 1:row
for j = i+1:row %analysis is performed accounting for
% symmetry constraint
C = bsxfun(@eq,A(i,:),A(j,:)'); %Tensor comparison
if(any(C(:))) %If some entry is non-zero you have equal elements
answers(i,j) = 1; %output
end
end
end
answers = answers + answers'; %symmetric
的輸出這裏是
answers =
0 0 1 1 0
0 0 0 0 1
1 0 0 1 0
1 0 1 0 0
0 1 0 0 0
當然
的answers
矩陣是對稱的,因爲你的關係是。
如果你有很多行和/或長行,Acorbe提出的解決方案可能會很慢。我已經檢查過,在大多數情況下,我在下面介紹的兩種解決方案應該快得多。如果您的矩陣只包含幾個不同的值(相對於矩陣的大小),那麼這應該工作非常快:
function rowMatches = find_row_matches(A)
% Returns a cell array with row matches for each row
c = unique(A);
matches = false(size(A,1), numel(c));
for i = 1:numel(c)
matches(:, i) = any(A == c(i), 2);
end
rowMatches = arrayfun(@(j) ...
find(any(matches(:, matches(j,:)),2)), 1:size(A,1), 'UniformOutput', false);
,當你有短行,即當size(A,2)
較小,這種其他替代可能會更快:
function answers = find_answers(A)
% Returns an "answers" matrix like in Acorbe's solution
c = unique(A);
answers = false(size(A,1), size(A,1));
idx = 1:size(A,1);
for i = 1:numel(c)
I = any(A == c(i), 2);
uMatch = idx(I);
answers(uMatch, uMatch) = true;
isReady = all(A <= c(i), 2);
if any(isReady),
idx(isReady) = [];
A = A(~isReady,:);
end
end
不起作用...?索引超過矩陣尺寸。 –
先試試你的方陣。它會工作。可能它只是行列大小的問題(在方陣中相等)。我會盡快解決。 – Acorbe
請幫忙。我仍然在等待:( –