Checking each element in a vector

조회 수: 38 (최근 30일)
GEON G BASTIAN
GEON G BASTIAN 2020년 1월 13일
댓글: Adam Danz 2020년 1월 14일
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

채택된 답변

Adam Danz
Adam Danz 2020년 1월 13일
편집: Adam Danz 2020년 1월 14일
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
Adam Danz
Adam Danz 2020년 1월 14일
Thanks @GEON G BASTIAN, if you have improvements you'd like to share, feel free to add them here.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Psychology에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by