How to create a vector with for loops and if statements
Show older comments
Creating a vector based on the following;
t = linspace(-1,2,3001);
- v = 1000*t when 0 <= t <= 1
- v = 0 otherwise
I've tried multiple variations of the following, never getting the desired resultant vector.
for index = t
if t>=0 & t<=1
v = 1000*t;
else
v = 0;
end
end
This results in a 1x1 vector with 0
Next, added v = t*0 instead of just 0
t = linspace(-1,2,3001);
for index = t
if t>=0 & t<=1
v = 1000*t;
else
v = t*0;
end
end
This gives me the appropriately sized vector, but it's just full of 0's
So I attempted to simplify further;
t = linspace(-1,2,3001);
for index = t
if t < 0
v = t*0;
elseif t>1
v = t*0;
else
v = 1000*t;
end
end
This gives me a linear vector v=1000*t for all values, as if my IF statements are being ignored.
I've come to the conclusion that I'm going about this in some fundamentally incorrect manner and would appreciate some guidance.
edit: Still working on this... I see that no matter what I've attempted, the result is always the last statement (regardless of conditions). Clearly doing something wrong here.
Thanks in advance.
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!