How to use a double index with a restriction under a for loop along with indicator function to calculate the occurrence of a given state

3 visualizaciones (últimos 30 días)
Dear all,
If we consider the following initial vector : x= [2 3 7 4 8 5 1 6] that would be updated according to a discrete uniform permutation (reshuffling numbers from 1 to 8). And I would like to have the following condition respected:
if abs (x(i)- x(i-j))= j then S(x)=1 every time this happens
where : i=2:8 and j=1:7
As there are 28 comparisons to be made (if we consider a matrix B with i in rows and j in columns then we have a 7x7 matrix, but we only consider the upper half including the diagonal) to avoid issues related to negative index . Perhaps the indicator function could be used.
Then B(i,i-j)= 1 every time the condition is respected otherwise zero.
Finally i would sum the number of ones obtained in S(x). I tried the following code but I am really not sure this is the right way to make such comparisons within the same vector. I get an (i , j ) matrix filled with zeros and one "1" always at the same location (2,1) whatever the content of x.
x= [2 3 7 4 8 5 1 6]
S=zeros(7,7)
for i=2:8
for j=1:7
while j<i
S(i,j)=(abs(x(i)-x(i-j))==j )
end
end
end

Respuestas (1)

Benjamin Großmann
Benjamin Großmann el 22 de Mayo de 2018
Sorry, i do not understand your condition and explanation for "if abs (x(i)- x(i-j))= j then S(x)=1". x is a vector. Do you want the vector x to be the index for S in your code (i and j are indices for s)?
Your while loop is infinitely running because the condition is always true (starting with i=2 and j=1, j is always less then i since they are not changing within the loop). Try to change "while" to "if", result should be okay. But you could also write the inner for-loop as
for j = 1:i-1
...
end
Then you dont have to worry about i-j being zero/negative. I think that your code shoud be okay then, but have a look at your for-loops. Most often one should try to avoid loops in Matlab.
Also, have a look at the functions perms and randperm.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by