Indexing Elements in an Array

2 views (last 30 days)
RPS19
RPS19 on 26 Nov 2019
Answered: Guillaume on 26 Nov 2019
Hello all, I am trying to access elements of an array only when the values of the third row (corresponding to angle in radians) are between certain values. The voltage values should be non zero only around angles of 0, but my code currently includes non zero values around 180 deg as well, so this is how I am trying to remedy that.
My code below is always returning q as being equal to 1 even though the angles oscillate between +/- 180 degress. Is there a different/better way that I should be indexing the values in the array? Any help would be greatly appreciated.
if sy(-0.87 < sy(3,:) < 0.87)
q = 1;
else
q = 0;
end
Voltage = q*K_y_Total.*y_dot;

Answers (1)

Guillaume
Guillaume on 26 Nov 2019
Apart from a blackboard, I'm not aware of any language where a < b < c is the proper way to test if a number is between two others.
In all programming languages that I know, a < b < c is equivalent to (a < b) < c and since the result of (a < b) is either true (1) or false (0), the expression is equivalent to either 0 < c or 1 < c depending on whether a is smaller than b. The proper way of writing such comparison has always been: a < b & b < c, or a < b && b < c if the arguments are all scalar (not the case for you).
Now, if you did write
if -0.87 < sy(3,:) & sy(3, :) < 0.87
You'd still have a problem since the result of that comparison is a logical vector and if you pass a logical vector to if, the if is only considered only true if all the elements of the vector are true.
I'm actually not really clear what you were trying to do with your sy(-0.87 < sy(3,:) < 0.87), even if you wrote it as
sy(-0.87 < sy(3, :) & sy(3, :) < 0.87)
it still doesn't make sense. It would work but it is bad notation since you're using a logical vector to index a 2D matrix. it is equivalent to
sy(1, -0.87 < sy(3, :) & sy(3, :) < 0.87)
and would return the elements of the 1st column of sy for which the 3rd column is within the required range.
I suspect that maybe you were trying to do this:
q = -0.87 < sy(3, :) & sy(3, :) < 0.87; %no if needed. q is a vector of 0s and 1s.

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!