Why the other value are not getting incremented in an array?
Afficher commentaires plus anciens
a=[1,2,3,4]
b=[1,2,3,4]
for i=1:4
for j=1:4
if(j>i||j~=i)
c(i)=p(j-i)
end
end
end
c =11 0 0 0
c =22 0 0 0
c =33 0 0 0
Subscript indices must either be real positive integers or logicals.
Réponses (2)
Guillaume
le 17 Sep 2015
Probably, you meant
c(i,j) = p(j-i); %or maybe c(j,i), use better variable names like row, col
Rather than having a for loop going over all values and only using the valid ones with an if, use a for loop that go over only the valid ones:
for row = 1:3
for col = row+1:4
c(row, col) = p(row-col);
end
end
The error is due to the if-clause
if (j>i||j~=i)
which is equivalent to
if j~=i
which is true also if j<=i, and in this case you use an invalid index <=0 in the expression
c(i)=p(j-i)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!