Filter löschen
Filter löschen

loop for matlab array

1 Ansicht (letzte 30 Tage)
best16 programmer
best16 programmer am 23 Nov. 2016
Bearbeitet: James Tursa am 23 Nov. 2016
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.

Antworten (3)

Geoff Hayes
Geoff Hayes am 23 Nov. 2016
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 Kommentare
best16 programmer
best16 programmer am 23 Nov. 2016
yes i know,i'm trying to display the result c in a edit text
Image Analyst
Image Analyst am 23 Nov. 2016
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.

Melden Sie sich an, um zu kommentieren.


Image Analyst
Image Analyst am 23 Nov. 2016
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 Kommentare
best16 programmer
best16 programmer am 23 Nov. 2016
the problem is how can we display all the c values in a edit text
Image Analyst
Image Analyst am 23 Nov. 2016
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?

Melden Sie sich an, um zu kommentieren.


Andrei Bobrov
Andrei Bobrov am 23 Nov. 2016
c = (a(:)*2 - 1)*b(:)';
or
c = (a(:)*2 - 1).*b(:);

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by