MATLAB: ‘for loop’ for beginners

basicbasic matlabfor loopsnegative numberspositive numbersvectors

I'm having trouble figuring out a for loop command. I'm trying to make a matlab script that allows the user to input a row vector, and then it outputs a new vector of 0's and 1's. 0's for negative numbers and 1's for non negative numbers.
so far what i have is:
v=input('Enter elements of vector: \n');
% after entering v,run below code

for i = 1:length(v)
if v(i) > 0
sprintf('v(%i)>0',i)
elseif v(i) <0
sprintf('v(%i)<0',i)
end
end
but when I finish, i get "Error: Unexpected MATLAB expression." So I guess I just need to know where I'm going wrong and what I need to do differently. I'm not sure how to make the loop output it when it's done either. Thanks in advance for your help!
edit: I also tried:
v=input('Enter elements of vector: \n');
% after entering v,run below code
for i = 1:length(v)
if v(i) > 0
v(i)=1
elseif v(i) <0
v(i)=0
else
v(i)=0
end
end
which also doesn't work. I'm not sure how to get the program to replace the values from the old vector with 0's and 1's based on whether or not they are positive. Thanks again.

Best Answer

Here's one way that works.
str = input('Enter elements of vector: \n', 's');
v = cell2mat(textscan(str, '%f,'))
% After entering v,run below code
for i = 1:length(v)
if v(i) > 0
v(i)=1
elseif v(i) <= 0
v(i)=0
end
end
Of course the for loop could be replaced by a vectorized solution
v = v>0;
Related Question