Hi, can anyone tell me what is the problem of this? It says "Operands to the || and && operators must be convertible to logical scalar values."
조회 수: 1 (최근 30일)
이전 댓글 표시
function [ x,niter ] = NewtonRaphson( x0,tol,nmax )
%DATA
N = 20;
niter = 0;
error = 1;
x0 = zeros(N-1,1);
dx = zeros(N-1,1);
while ((error > tol) && (niter < nmax))
niter = niter + 1;
x = x0 - ((F_springs(x0))./(J_springs(x0)));
x0 = x;
error = max(abs(x-F_springs(x0)));
end
for i = 2:N-2
dx(i) = x(i)-x(i-1);
end
end
댓글 수: 0
채택된 답변
Walter Roberson
2017년 12월 17일
x0 = zeros(N-1,1);
so x0 is a vector.
x = x0 - ((F_springs(x0))./(J_springs(x0)));
x0 = x;
with x0 being a vector, x will be a vector; and then you assign it to x0 so x0 will stay a vector.
error = max(abs(x-F_springs(x0)));
with x and x0 being vectors, error is going to be a vector.
while ((error > tol) && (niter < nmax))
error is a vector, so error > tol is a vector. You now have a vector on the left side of && . But the && operator is strictly for scalars, never for vectors. For vectors you would need to use the & operator, as in
while ((error > tol) & (niter < nmax))
As niter<nmax is a scalar, the effect of that would be to calculate (niter < nmax) and to "and" it with each element of (error > tol), giving a vector of results.
The definition of if or while with a vector is to consider the condition to be true only of all of the items in the vector are non-zero. This would be equivalent to
while all((error > tol) & (niter < nmax))
which would stop as soon as any location in error was not greater than tol.
You should re-think why you want x0 to be a vector. If you have a good reason for it being a vector, then think about whether you truly want the entire vector to be involved in the calculations each time.
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!