Why the other value are not getting incremented in an array?
Ältere Kommentare anzeigen
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.
Antworten (2)
Guillaume
am 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)
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!