How to make a +5 (or any +number) jump in array values inside a for loop?
13 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
So when line 0 condition is met, I want the for loop to jump 5 rows from the given data set of a single column. So when count1 ==5 , I want the loop to skip 5 rows from the column and take the 6th element as the new reference. [8,8,8,8,8,9,6,546,6,5,6,4,5,5,5,5,5]. In this dataset, the count value should be 2. Now what the issue is that the code given below does not skip to the 6th reference value to compare the next 5 values. I tried line 1 and 2 but those did not work or have any effect on the code.
count=0;
count1=0;
for i=1:length(data)-4
for j=i+1:i+4
if data(i)~=data(j)
count1=0;
break;
else
count1=count1+1;
end
if count1==5 % line 0
count=count+1;
%data(i,1)=data(i+5,1); //line 1
%data(i)=data(i+5); //line 2
else
continue;
end
end
end
5 Kommentare
Jan
am 1 Mär. 2021
Bearbeitet: Jan
am 1 Mär. 2021
I do not know, what "the first one" and "the second one" are.
What does "there are 4 of the 5 consecutive numbers of the same starting number" mean?
As far as I understand, you want to:
count the number of blocks, which have 5 equal elements.
This is a much shorter description, isn't it?
Antworten (1)
Jan
am 1 Mär. 2021
Bearbeitet: Jan
am 1 Mär. 2021
function n = RunLength_count(x)
d = [true, diff(x(:).') ~= 0, true]; % TRUE if values change
n = diff(find(d)); % Number of repetitions
end
Then:
x = [8,8,8,8,8,9,6,546,6,5,6,4,5,5,5,5,5];
n = RunLength_count(x);
Result = sum(floor(n / 5))
USing floor(n / 5) let all blocks with less then 5 element be counted as zeros. 9 consecutive elements are counted as 1 block and 10 as 2 blocks.
You can do this with a loop also, but this is less elegant and efficient:
count = 0;
block = 0;
q = nan; % Initial element to compare with
for k = 1:numel(data)
if data(k) == q % Element equals former one
block = block + 1;
if block == 5
count = count + 1;
block = 0;
end
else % A new value
q = data(k);
block = 1;
end
end
You do not need a 2nd loop.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!