# Invalid use of operator.

조회 수: 6(최근 30일)
Rebecca D'Onofrio 2021년 9월 6일
편집: Jan 2021년 9월 6일
for ii=2:26
for jj=1:26
for ii~=jj
A(ii,jj)=[A(ii,jj)+ELREM(ii)+IN(ii)];
end
end
end
why does it give "invalid use of the operator in the 3rd line?

댓글을 달려면 로그인하십시오.

### 채택된 답변

Jan 2021년 9월 6일
편집: Jan 2021년 9월 6일
Replace
for ii~=jj
by
if ii~=jj
A for command must have the structure:
for counter = a:b
and the ~= operator is not allowed here.
By the way, [ ] is Matlab's operator for a concatenation. In
A(ii, jj) = [A(ii,jj) + ELREM(ii) + IN(ii)];
you do not concatenate anything, but there is one element only. So this is nicer and slightly faster:
A(ii, jj) = A(ii,jj) + ELREM(ii) + IN(ii);
A vectorized version of your code:
v = 1:26;
for ii = 2:26
m = (v ~= ii);
A(ii, m) = A(ii, m) + ELREM(ii) + IN(ii);
end

댓글을 달려면 로그인하십시오.

### 추가 답변(1개)

Walter Roberson 2021년 9월 6일
Immediately after the for keyword, there must be an unindexed variable. Immediately after that there must be an equal sign, =
After that,there are a few different possibilities:
1. You can have an expression then a colon and then another expression, such as for k = 1:10
2. You can have an expression then a colon then another expression then a colon and then a third expression, such as for k = 1:2:9
3. You can have a general expression that computes a scalar or vector or array result, such as for k = sqrt(x.^2+y.^2)
None of the valid syntaxes include the possibility of a ~= at that point.
In the above list of possibilities, the third one involves fully evaluating the expression and recording all of the values for later use. The first and the second look very much the same, and act very much the same: it is as if the values were all recorded at the time the for statement is encountered. The difference between the first two and the third, is that in practice MATLAB special-cases the : and :: variations and does not fully evaluate the expression to the right. For example MATLAB can deal with for k = 1 : inf without having to generate the infinite list of values 1, 2, 3, and so on, and store them all for later use -- whereas the third option, any expression other than : or :: expression, fully evaluates and records before starting the loop.
for ii=2:26
for jj=1:26
if ii~=jj
A(ii,jj)=[A(ii,jj)+ELREM(ii)+IN(ii)];
end
end
end

댓글을 달려면 로그인하십시오.

### 범주

Find more on Get Started with MATLAB in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!