循环检查数组中每个元素的重复次数 - 在 while 期间卡住
Looping to check for number of repeats of each element in array - stuck during while
假设我有以下数组,
x = [1, 2, 3, 4, 5, 5, 6, 1, 1];
我正在尝试编写一个循环遍历每个元素并检查是否有重复的函数。例如,"does x(1) == x(2)
OR does x(1) == x(3)
OR ... does 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
然而,代码似乎从未通过第一次迭代,并且在 "Busy" 中闲置。如何更好地实现这段代码?
您的问题是因为您从未在 while
内更改 indexSum
或 N
,因此循环条件始终为真!
你可以不用 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
假设我有以下数组,
x = [1, 2, 3, 4, 5, 5, 6, 1, 1];
我正在尝试编写一个循环遍历每个元素并检查是否有重复的函数。例如,"does x(1) == x(2)
OR does x(1) == x(3)
OR ... does 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
然而,代码似乎从未通过第一次迭代,并且在 "Busy" 中闲置。如何更好地实现这段代码?
您的问题是因为您从未在 while
内更改 indexSum
或 N
,因此循环条件始终为真!
你可以不用 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