Creating new vector and using IF correct or loop?

1 view (last 30 days)
Hello,
I need some help with my matlab code.
I have two vectors of data: "position" and "time", The position vector has a maximum value of ~2 and a minimum value of ~-1. Booth vector are of 1x500000 points. My time vector looks like this: time=(0:length(position)-d)*dt %dt is the value between each point (2e-4), delta time
I want to be able to construct a new vector called "force".
This vector should be created by multiplication the position vector with a certain value. But I have different values for this multiplication. If the current value of the position is lower than 0.5, it should be multiplied with a certain value, x If it is between 0.5 and 1.5, it should be multiplied with a value, y. And so on...
I should then also be able to plot "time" vs "force".
I guess I should use some if and/or elseif commands. But how do I get it right?
Thank you.
  1 Comment
Image Analyst
Image Analyst on 25 Sep 2014
Make it easy for people to help you by attaching a data file and a snippet of code to read it in to some variables.

Sign in to comment.

Accepted Answer

Adam
Adam on 25 Sep 2014
Just put together a multiplication vector as e.g.
multVec = zeros( size( position ) );
multVec( position < 0.5 ) = m1;
multVec( 0.5 <= position & position < 1.5 ) = m2;
...
Then:
force = position .* multVec;

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 25 Sep 2014
Edited: Andrei Bobrov on 25 Sep 2014
v = [-inf,.5,1.5,inf];
[~,ii] = histc(position,v);
m = [2 8 15]'; % example as m = [m1,m2,m3];
force = m(ii).*position;

Categories

Find more on Loops and Conditional Statements 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!