MATLAB Answers

Expected a scalar and it should be a scalar

6 views (last 30 days)
I don't understand why I get this error when it should actually be a scalar:
I've tried removing the (:), and "if all (delta_Fx) < 0 but it shows the same error.

  1 Comment

darova on 30 May 2019
Can you please attach entire code?

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 30 May 2019
Edited: Stephen Cobeldick on 30 May 2019
If delta_Fx is not scalar, then the output of
-delta_Fx > delta_Fx_max
will not be scalar either. You need to correctly handle all non-scalar conditions, not just the first one.
However it is quite likely that your approach using if is incorrect anyway. It appears that you are attempting an element-wise operation (which if does not do without a loop), namely replace values whose magnitude lies outside some value range, and so you probably should be doing something like this:
delta_Fx = max(-delta_Fx_max,min(delta_Fx_max,delta_Fx))


Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 30 May 2019
Delta_Fx is an vector, so do you want to enter the "if" if any one is true, or only if ALL are true?
Use any or all as appropriate, according wo whatever you want. Some possible options depending on exactly what you want:
if any(delta_Fx < 0 & -delta_Fx > delta_Fx_max)
if all(delta_Fx < 0 & -delta_Fx > delta_Fx_max)
if all(delta_Fx < 0) && all(-delta_Fx > delta_Fx_max)
if all(delta_Fx < 0) && any(-delta_Fx > delta_Fx_max)
if any(delta_Fx < 0) && all(-delta_Fx > delta_Fx_max)
if any(delta_Fx < 0) && any(-delta_Fx > delta_Fx_max)
Note how sometimes I used & and sometimes used &&. I used a single & if I want to AND two multi-element vectors, and && if I want to AND two one-element boolean.


Sign in to comment.


Community Treasure Hunt

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

Start Hunting!

Translated by