说我有以下数组,
x = [1, 2, 3, 4, 5, 5, 6, 1, 1];
我试图编写一个遍历每个元素的函数,并检查是否有重复。例如," x(1) == x(2)
或x(1) == x(3)
或... x(1) == x(9)
"。到目前为止,我有以下代码:
N = length(x);
sharedPosition = zeros(1, N);
for i = 1:N
for j = 1:N
indexSum = i + j;
while indexSum <= N
isShared = x(1, i) == x(1, i+j);
sharedPosition(1, i) = sum(isShared);
end
end
end
然而,代码似乎永远不会超过第一次迭代并且使用&#34;忙碌&#34;空闲。如何更好地实现此代码?
答案 0 :(得分:1)
您的问题是因为您永远不会在indexSum
内更改N
或while
,因此循环条件始终为真!
您可以在没有while
且只有一个for
% size and numel are usually preferred over length, as it's ambiguous which dimension
% you are getting the "length" of.
N = numel(x);
sharedPosition = zeros(1, N);
% Loop over values
for ii = 1:N
% Store the number of times the given value occurs
% MATLAB can compare a scalar to an entire array, no need to loop again.
sharedPosition(ii) = sum(x(ii) == x);
end