how to calculate the value?
조회 수: 10 (최근 30일)
이전 댓글 표시
I have the following values and want to calculate value of alpha such that alpha >=0;
a=rand(1,49);
b=rand(49,49);
c=rand(1,49);
alpha = (-b+real(sqrt(b^2-4*a*c')))/(2*a);
however I'm getting the value of alpha same which should not be true. Is there any error in my code.
댓글 수: 1
채택된 답변
Stephen23
2017년 9월 27일
편집: Stephen23
2017년 9월 27일
You really need to learn the difference between matrix operations and array operations:
and then review what you have written (hint: you need array operations, not matrix operations).
To give you a working solution you should also tell us what MATLAB version you are using.
댓글 수: 2
Stephen23
2017년 9월 27일
편집: Stephen23
2017년 9월 27일
Implicit array expansion was introduced in R2016b, so the simplest solution would be to use bsxfun:
a = rand(49,1);
b = rand(49,49);
c = rand(1,49);
alpha = bsxfun(@rdivide,-b+real(sqrt(b.^2-4*a*c)),2*a);
Note that I specified the exact orientation of the input vectors a and c! If you really want to accept a and c with either orientation, you could do this:
alpha = bsxfun(@rdivide,-b+real(sqrt(b.^2-4*a(:)*c(:).')),2*a(:));
but I would suggest that you learn to be strict about the required orientation rather than writing sloppy code like that.
And just like any other code you should check the output by hand to make sure that it really gives the output that you expect.
추가 답변 (1개)
Jan
2017년 9월 27일
편집: Jan
2017년 9월 27일
You can examine the parts of the code:
% alpha = (-b+real(sqrt(b^2-4*a*c')))/(2*a)
a * c'
-4 * a * c'
b ^ 2
b ^ 2 - 4 * a * c'
sqrt(b^2-4*a*c')
-b + real(sqrt(b^2-4*a*c'))
(-b+real(sqrt(b^2-4*a*c'))) / (2*a)
In which step to the results differ from your expectations? Note that all you gave us is the Matlab code and the claim, that the output "should not be true". How can we know, if there is an error in the code, when all we know is "such that alpha >=0". Perhaps your code is wrong or the expectations that alpha is greater than 0.
Kitty, we cannot read your mind. Please learn, that you have to provide much more details in your questions. Use the debugger and check your results by your own at first. And if you do not get any clue what happens, explain, what you have tried so far and ask more specifically. I cannot guess if you really want:
b ^ 2 % which is: b * b.'
or
b .^ 2
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!