Checking each element in a vector

38 views (last 30 days)
Hello guys, I want to check each element of a vector v and if any element in the vector is equal to or in between -0.9 and 0.9, then i want to calculate d using one formula and if the element is not between -0.9 and 0.9, I want to use another formula. Also after each iteration, I want to display the variable d.
So for example if my vector v = -1:0.1:1 then the result should be
0.35
0.3354
0.3354
0.3354
0.3354
0.3354
0.3354
0.3354
0.3354
0.3354
0.3354
0.3354
0.3354
0.3354
0.3354
0.3354
0.3354
0.3354
0.3354
0.35
but for me, the 0.35 value is not being displayed but for every iteration, the same value 0.3354 is being displayed .
v = -1 :0.1: 1;
for i= 1:length(v)
if any(v >= -0.9 & v<=0.9)
d = sqrt((h^2)+(s^2));
if any(v<-0.9 & v>0.9)
g= sqrt(s^2 + (v-0.9)^2);
d = sqrt(g^2 + h^2);
end
end
disp(d);
end

Accepted Answer

Adam Danz
Adam Danz on 13 Jan 2020
Edited: Adam Danz on 14 Jan 2020
Note, we don't know what h, s, and g are but I'm guessing they are numeric vectors of the same size as v in which case, either of these two solutions should work (obviously not tested). If they are not vectors or not the same size as v, it would probably be easy to adapt either of these solutions to their size and class.
Loop method
If you're using a loop, you should only access a single element of v at a time by indexing v(i).
v = -1 :0.1: 1;
for i= 1:numel(v) % replaced length() with numel()
if v(i) >= -0.9 || v(i)<=0.9
d = sqrt((h^2)+(s^2));
elseif v(i)<-0.9 || v(i)>0.9 % this line can be replace with just 'else'
g= sqrt(s^2 + (v(i)-0.9)^2);
d = sqrt(g^2 + h^2);
end
end
disp(d);
Vectorization method
However, you don't need a loop. The method below is more efficient and easier to read. Vectorization is kind of the point of using Matlab over competitors.
v = -1 :0.1: 1;
idx = v <= -0.9 | v >= 0.9;
d = nan(size(v));
d(idx) = (sqrt(s(idx).^2 + (v(idx)-0.9).^2) + h(idx).^2).^2;
d(~idx) = sqrt((h(~idx).^2)+(s(~idx).^2));
  1 Comment
Adam Danz
Adam Danz on 14 Jan 2020
Thanks @GEON G BASTIAN, if you have improvements you'd like to share, feel free to add them here.

Sign in to comment.

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!