count number of indices

46 vues (au cours des 30 derniers jours)
gummiyummi
gummiyummi le 6 Août 2020
Modifié(e) : Matt J le 8 Août 2020
I have an array with 7 columns filled with data. Column 2 has 0s then a 1 then 0s and then a -1 in repeating order. The number of 0s between a 1 and a -1 varies.
In column 2 I want to count for each cell which has the value 1, the number of cells there are until the next cell with value -1. If the count is bigger than 100, I want to add the index of the cell with value 1, to the first available cell in column 8.
I have come furthest with the following code:
n=1;
for i = 1:length(arrayA)
if arrayA(i,2) == 1
if abs(find(arrayA(i,2)==1) - find(arrayA(:,2)==-1)) > 200
arrayA(n,8)=i;
n=n+1;
end
end
end
yet column 8 still doesn't have any values when I run the whole thing.
Pretty sure the problem is line 3 but have no more ideas left on how I could make it work...
  2 commentaires
Rik
Rik le 6 Août 2020
Where do you define n? Also, find might return multiple values, in which case you have a logical array for you if statement, which I always have to look up what it does. Are you sure you implemented that line correctly?
gummiyummi
gummiyummi le 7 Août 2020
I defined n before the for loop as follows
n = 1;
sorry forgot to include that

Connectez-vous pour commenter.

Réponse acceptée

gummiyummi
gummiyummi le 7 Août 2020
n=1;
I=find(arrayA(:,2)==1);
J=find(arrayA(:,2)==-1);
for k=1:length(I)
if J(k)-I(k)>100
arrayA(n,8)=pos_one(k);
arrayA(n,9)=neg_one(k);
n=n+1;
end
end
  2 commentaires
Rik
Rik le 7 Août 2020
If the number of elements in I and J are equal, you can use find to remove the loop.
gummiyummi
gummiyummi le 7 Août 2020
ah cool thanks!

Connectez-vous pour commenter.

Plus de réponses (1)

Matt J
Matt J le 6 Août 2020
Modifié(e) : Matt J le 6 Août 2020
Using group1s from the File Exchange
col2=arrayA(:,2);
I=find(col2==1);
H=histcounts(nonzeros(group1s(~abs(col2))));
loc=I(H(2:2:end)>100);
arrayA(loc,8)=loc;
  3 commentaires
gummiyummi
gummiyummi le 7 Août 2020
group1s doesn't work since my array never has consecutive 1s
Matt J
Matt J le 8 Août 2020
Modifié(e) : Matt J le 8 Août 2020
It worked fine for me:
col2=[0,1,0,-1,0,1,0,-1,0,1,zeros(1,101),-1].';
I=find(col2==1);
H=histcounts(nonzeros(group1s(~abs(col2))));
loc=I(H(2:2:end)>100)
Notice that only the 1 at position loc=10 is picked out:
loc =
10

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by