I am struggling with an iteration loop.
I have a vector containing all the velocity values.
I need to create a vector for the displacement values to be plotted against time.
Now mathematically this is rather simple however I can't get my 'for' loop to work at all! It keeps just returning the values of velocity on the graph. The biggest indicator that the script is wrong is the fact that displacement should never decrease (there are no negative velocity values) yet mine clearly does
Here is my current loop:
for k = 2:length(v);
distance(k) = (0.1*(v(k-1))) + (0.1*(v(k)));
end
Note that v = velocity, k is the loop counter, and the time step between v values is 0.1

댓글 수: 3

Stephen23
Stephen23 2016년 5월 23일
편집: Stephen23 2016년 5월 24일
Your code is equivalent to this (using vectorized code):
[0, 0.1 * (v(1:end-1) + v(2:end))]
basically you take 0.1 times the sum of adjacent pairs of values, with a leading zero stuck on the end. If this is not what you intended to calculate, then you should tell us what you are trying to do, and provide correct input and output examples for us to try our code on.
sgc321
sgc321 2016년 5월 23일
So would that sit inside the 'for' loop or is it a stand alone statement? as I cant see a k variable
Stephen23
Stephen23 2016년 5월 23일
편집: Stephen23 2016년 5월 23일
No loop is required. I just showed you a simpler way of doing what your code actually does, without any loop. It does not solve your task of implementing the trapezoidal integration!

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

답변 (1개)

Stephen23
Stephen23 2016년 5월 23일
편집: Stephen23 2016년 5월 24일

0 개 추천

Why bother using a loop? MATLAB code can be so much neater!
>> v = [1,2,3,2,3,1];
>> s = 0.1; % step size
>> x = s*(1:numel(v));
>> sum(s*(v(2:end)+v(1:end-1))/2)
ans = 1.1000
But really there is no point in reinventing the wheel: just use trapz:
>> trapz(x,v)
ans = 1.1000

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2016년 5월 23일

편집:

2016년 5월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by