loop for matlab array
이전 댓글 표시
i have a problem with for loop.we have a vector a=[0 1 1 1 0] and a vector b=[1 1 1 1 1]
for i = 1:length(a)
if a(i)==0
c = [-1.*b] ;
else if a(i)==1
c = [1.* b];
end
end
the loop works only for a(1)=0 and stops.
답변 (3개)
Geoff Hayes
2016년 11월 23일
Try removing the space between the else if. Re-write this as
if a(i)==0
c = [-1.*b] ;
elseif a(i)==1
c = [1.* b];
end
댓글 수: 4
best16 programmer
2016년 11월 23일
Image Analyst
2016년 11월 23일
What are you trying to do? Each iteration you make up a c array which is different on each iteration. c is not a single number you know. It's a vector.
best16 programmer
2016년 11월 23일
Image Analyst
2016년 11월 23일
Then just do
handles.edit1.String = sprintf('%d ', c);
This will convert the vector to a string and put it into the edit text box on your GUI.
Image Analyst
2016년 11월 23일
Maybe you wanted elseif instead of "else if". This works and does several iterations:
a=[0 1 1 1 0]
b=[1 1 1 1 1]
for i = 1:length(a)
if a(i)==0
c = [-1.*b]
elseif a(i)==1
c = [1.* b]
end
end
Of course there are better ways to do that and no experienced MATLAB programmer would do that operation like that.
댓글 수: 3
best16 programmer
2016년 11월 23일
편집: best16 programmer
2016년 11월 23일
best16 programmer
2016년 11월 23일
Image Analyst
2016년 11월 23일
They will all be displayed because there is no semicolon at the end of the line. Did you actually try it and look in the command window?
Andrei Bobrov
2016년 11월 23일
c = (a(:)*2 - 1)*b(:)';
or
c = (a(:)*2 - 1).*b(:);
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!