relative error: Error using ==> mtimes

조회 수: 6 (최근 30일)
NH
NH 2012년 9월 16일
Hello I am trying to get the relative error for sinx=sqrt(1-cos^2(x) and getting error with this matlab code:
clear
clc
x=logspace(-1,-10,10);
lhs=sin(x);
t=cos(x);
rhs=sqrt(1-cos(x)*cos(x));
abserr=abs(lhs-rhs);
Rel=abs((lhs-rhs)/lhs);
disp('x error rel.error')
disp('--------------------')
for i=1:10
disp(sprintf('%22.15e %22.15e %22.15e\n',x(i),abserr(i),Rel(i)))
end
end
??? Error using ==> mtimes Inner matrix dimensions must agree.
Error in ==> Q at 6 rhs=sqrt(1-cos(x)*cos(x));
any idea? thanks

채택된 답변

Jan
Jan 2012년 9월 16일
편집: Jan 2012년 9월 16일
rhs = sqrt(1 - cos(x) .* cos(x))
While * performs the matrix multiplication, .* multiplies elementwise.

추가 답변 (1개)

NH
NH 2012년 9월 16일
thank you thats solved the problem. Now after i run it i get this new error:
?? Attempted to access Rel(2); index out of bounds because numel(Rel)=1.
Error in ==> Q at 11 disp(sprintf('%22.15e %22.15e %22.15e/n',x(i),abserr(i),Rel(i)))
clear
clc
x=logspace(-1,-10,10);
lhs=sin(x);
rhs=sqrt(1-cos(x).*cos(x));
abserr=abs(lhs-rhs);
Rel=abs((lhs-rhs)/lhs);
disp('x error rel.error')
disp('--------------------')
for i=1:10
disp(sprintf('%22.15e %22.15e %22.15e\n',x(i),abserr(i),Rel(i)))
end
end
  댓글 수: 2
Jan
Jan 2012년 9월 17일
편집: Jan 2012년 9월 17일
  1. Please post a new thread for a new problem.
  2. Use the debugger to find the reasons for the size of Rel: Set a breakpoint in the line Rel=abs((lhs-rhs)/lhs) to find out, that exactly the same argument of matrix versus elementwise operations concerns the division also. Therefore you need ./ instead of / . Surprised?
NH
NH 2012년 9월 17일
1. Thank you, next time I will. 2. Wow! thank you fore your advice exactly what I needed.

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

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by