how to calculate the value?
21 次查看(过去 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 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!