'for loop' for beginners?

4 次查看(过去 30 天)
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.

采纳的回答

Image Analyst
Image Analyst 2014-10-8
编辑:Image Analyst 2014-10-8
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 个评论
Image Analyst
Image Analyst 2014-10-8
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 2014-10-8
oh wow, jeez thank you so much.

请先登录,再进行评论。

更多回答(1 个)

Iain
Iain 2014-10-8
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by