フィルターのクリア

'for loop' for beginners?

4 ビュー (過去 30 日間)
Andrew Ardolino
Andrew Ardolino 2014 年 10 月 8 日
コメント済み: Andrew Ardolino 2014 年 10 月 8 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by