# the mysterious for loop

2 ビュー (過去 30 日間)
peter karlsson 2019 年 11 月 23 日
Commented: Rena Berman 2019 年 12 月 12 日
okey, I am going to create a program that will find a specifit value in a graf
the distance:km i a 1:1000 vector. the y axis
spped_kmph is the same. the x axis
in this program i can put in a single value like 5 and i will find how fast the car was at that point
THE PROBLEM: i Want to put in a vector so i can find the speed at more than 1 point at the time but when i put in a vector i get the message ( Operands to the || and && operators must be convertible to logical scalar values. )
Can someone figure out the for loop i need to put in?
So if i put in a vecor x = [4:10] it will go throuh all those values one by one and in the end sopt out 6 values for ''v''
function v=velocity_(x, route)
index = findpos(distance_km', x);
%i need to put in a for loop here
x1 = distance_km(index-1);
x2 = distance_km(index);
y1 = speed_kmph(index-1);
y2 = speed_kmph(index);
v = y1 * (x-x2)./(x1-x2)+y2*(x-x1)./(x2-x1)
end
------
findpos is this function
------
function index = findpos(vector,val)
vMAX = length(vector);
x=1
if val < vector(1) || val > vector(vMAX)
index = -1;
elseif val == vector(1)
index = 2;
else
while val > vector (x)
x = x+1;
end
index = x;
end

#### 1 件のコメント

Rena Berman 2019 年 12 月 12 日

サインイン to comment.

### 採用された回答

Star Strider 2019 年 11 月 23 日
The doubled logical operators are for scalar logical comparisons. Use single logical operators for vector comparisons. The any and all functions are also useful in this context.

#### 4 件のコメント

Star Strider 2019 年 11 月 24 日
As always, my pleasure!
A for loop should be relatively straightforward to write to loop through the vector. You will need to index the variables that you want to return from the function, so for example:
for k = 1:numel(x)
... CODE ...
v(k) = y1 * (x-x2)./(x1-x2)+y2*(x-x1)./(x2-x1)
end
peter karlsson 2019 年 11 月 24 日
thanks again. I see now that it doesnt matther what i put in
If i write index = findpos(distance_km, 20:23) it will just take the first number (20) I guess that it is because i have index = x; in the bottum of the second code. Can i change that to something els so my index can be a vector?
Star Strider 2019 年 11 月 24 日
As always, my pleasure.
I do not understand what you are doing.
I encourage you to experiment to see what works.

サインイン to comment.

Walter Roberson 2019 年 11 月 23 日
function index = findpos(vector, vals)
index = interp1(vector, 1:length(vector), vals, 'previous');
index(isnan(index)) = -1;
end

#### 0 件のコメント

サインイン to comment.

サインイン してこの質問に回答します。

Translated by