Invalid use of operator.

1 vue (au cours des 30 derniers jours)
Rebecca D'Onofrio
Rebecca D'Onofrio le 6 Sep 2021
Modifié(e) : Jan le 6 Sep 2021
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?

Réponse acceptée

Jan
Jan le 6 Sep 2021
Modifié(e) : Jan le 6 Sep 2021
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

Plus de réponses (1)

Walter Roberson
Walter Roberson le 6 Sep 2021
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

Catégories

En savoir plus sur Biological and Health Sciences dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by