필터 지우기
필터 지우기

'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 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