'for loop' for beginners?

2 views (last 30 days)
Andrew Ardolino
Andrew Ardolino on 8 Oct 2014
Commented: Andrew Ardolino on 8 Oct 2014
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.

Accepted Answer

Image Analyst
Image Analyst on 8 Oct 2014
Edited: Image Analyst on 8 Oct 2014
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;
  5 Comments
Image Analyst
Image Analyst on 8 Oct 2014
At the prompt when it's waiting for your input, type
1, 0, -3, 6, 2, -7
instead of
[1 0 -3 6 2 -7]
Andrew Ardolino
Andrew Ardolino on 8 Oct 2014
oh wow, jeez thank you so much.

Sign in to comment.

More Answers (1)

Iain
Iain on 8 Oct 2014
The error is because you're trying to get the user to enter a list of numbers with a function that only allows ONE number to be input.
If you replace:
v=input('Enter elements of vector: \n');
with
v = [4 5 3 6 1 -34 -56];
How you get the list of numbers from the user is up to you - you can either put it in a loop (while loop), or you can change your code to accept an input, then have the user call it, like sin([0 pi/2 pi])
You'll see that it works.

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!