how to calculate the value?

19 views (last 30 days)
kitty varghese
kitty varghese on 27 Sep 2017
Edited: Jan on 27 Sep 2017
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 Comment
Torsten
Torsten on 27 Sep 2017
Edited: Torsten on 27 Sep 2017
What is the equation you are trying to solve ?
It appears strange to me that a and b are vectors and b is a Matrix.
Best wishes
Torsten.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 27 Sep 2017
Edited: Stephen23 on 27 Sep 2017
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 Comments
kitty varghese
kitty varghese on 27 Sep 2017
@Stephen I'm working on MATLAB Version: 8.1.0.604 (R2013a)
Stephen23
Stephen23 on 27 Sep 2017
Edited: Stephen23 on 27 Sep 2017
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.

Sign in to comment.

More Answers (1)

Jan
Jan on 27 Sep 2017
Edited: Jan on 27 Sep 2017
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

Tags

Community Treasure Hunt

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

Start Hunting!