Checking each element in a vector
37 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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
2020-1-14
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!